(Translated by https://www.hiragana.jp/)
Autoboxing and Unboxing in Java - GeeksforGeeks
Open In App

Autoboxing and Unboxing in Java

Last Updated : 20 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

In Java, primitive data types are treated differently so do there comes the introduction of wrapper classes where two components play a role namely Autoboxing and Unboxing. Autoboxing refers to the conversion of a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is: 

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Unboxing on the other hand refers to converting an object of a wrapper type to its corresponding primitive value. For example conversion of Integer to int. The Java compiler applies to unbox when an object of a wrapper class is: 

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.
Primitive Type Wrapper Class
boolean Boolean
byte Byte
char Character
float  Float
int  Integer
long Long
short  Short
double Double

The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing. Now let us discuss a few advantages of autoboxing and unboxing in order to get why we are using it. 

  • Autoboxing and unboxing lets developers write cleaner code, making it easier to read.
  • The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

Example 1:

Java




// Java program to illustrate the Concept
// of Autoboxing and Unboxing
 
// Importing required classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an Integer Object
        // with custom value say it be 10
        Integer i = new Integer(10);
 
        // Unboxing the Object
        int i1 = i;
 
        // Print statements
        System.out.println("Value of i:" + i);
        System.out.println("Value of i1: " + i1);
 
        // Autoboxing of character
        Character gfg = 'a';
 
        // Auto-unboxing of Character
        char ch = gfg;
 
        // Print statements
        System.out.println("Value of ch: " + ch);
        System.out.println(" Value of gfg: " + gfg);
    }
}


Output:

Let’s understand how the compiler did autoboxing and unboxing in the example of Collections in Java using generics.

Example 2:




// Java Program to Illustrate Autoboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty Arraylist of integer type
        ArrayList<Integer> al = new ArrayList<Integer>();
 
        // Adding the int primitives type values
        // using add() method
        // Autoboxing
        al.add(1);
        al.add(2);
        al.add(24);
 
        // Printing the ArrayList elements
        System.out.println("ArrayList: " + al);
    }
}


Output

ArrayList: [1, 2, 24]

Output explanation: 

In the above example, we have created a list of elements of the Integer type. We are adding int primitive type values instead of Integer Object and the code is successfully compiled. It does not generate a compile-time error as the Java compiler creates an Integer wrapper Object from primitive int i and adds it to the list. 

Example 3:

Java




// Java Program to Illustrate Autoboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of integer type
        List<Integer> list = new ArrayList<Integer>();
 
        // Adding the int primitives type values by
        //  converting them into Integer wrapper object
        for (int i = 0; i < 10; i++)
 
            System.out.println(
                list.add(Integer.valueOf(i)));
    }
}


Output

true
true
true
true
true
true
true
true
true
true

Another example of auto and unboxing is to find the sum of odd numbers in a list. An important point in the program is that the operators remainder (%) and unary plus (+=) operators do not apply to Integer objects. But still, code compiles successfully because the unboxing of Integer Object to primitive int value is taking place by invoking intValue() method at runtime. 

Example 4:

Java




// Java Program to Illustrate Find Sum of Odd Numbers
// using Autoboxing and Unboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // To sum odd numbers
    public static int sumOfOddNumber(List<Integer> list)
    {
 
        // Initially setting sum to zero
        int sum = 0;
 
        for (Integer i : list) {
 
            // Unboxing of i automatically
            if (i % 2 != 0)
                sum += i;
 
            // Unboxing of i is done automatically
            // using intvalue implicitly
            if (i.intValue() % 2 != 0)
                sum += i.intValue();
        }
 
        // Returning the odd sum
        return sum;
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of integer type
        List<Integer> list = new ArrayList<Integer>();
 
        // Adding the int primitives type values to List
        for (int i = 0; i < 10; i++)
            list.add(i);
 
        // Getting sum of all odd numbers in List
        int sumOdd = sumOfOddNumber(list);
 
        // Printing sum of odd numbers
        System.out.println("Sum of odd numbers = "
                           + sumOdd);
    }
}


Output

Sum of odd numbers = 50



Previous Article
Next Article

Similar Reads

Output of Java programs | Autoboxing and Unboxing
Prerequisite - Autoboxing and unboxing in Java 1)What is the output of the following program? class Main { public static void main(String[] args) { Double x1, y1, z1; double x2, y2, z2; x1 = 10.0; y1 = 4.0; z1 = x1 * x1 + y1 * y1; x2 = 10.0; y2 = 4.0; z2 = x2 * x2 + y2 * y2; System.out.print(z1 + &quot; &quot;); System.out.println(z2); } } Options:
3 min read
Method Overloading with Autoboxing and Widening in Java
Let us go through the basic pre-requisites such as Method Overloading, Autoboxing, and Unboxing. So method overloading in java is based on the number and type of the parameters passed as an argument to the methods. We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler
7 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Difference between a Java Application and a Java Applet
Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications, it can be run with or without it. Java Applet is a Java program that can be embedded into a web pa
3 min read
Difference between Java IO and Java NIO
Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO API's. In this article, the difference between these two IO pack
3 min read
Difference between Java and Core Java
Java is a very famous language that is based on the object-oriented programming concepts. It is the successor of the C and C++ languages. It was developed by Sun Microsystems. Core Java is a term used by Sun Microsystems to refer to the Java to standard edition J2SE. This is the parent of all other editions of Java used on internet sites. It has a
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg