Introduction to Autoboxing and Unboxing in Java
Autoboxing is the Java compiler’s automatic conversion between the primitive types and their corresponding object wrapper classes, i.e., conversion from int to Integer, double to Double, etc. Unboxing is the automatic conversion from wrapper class objects to their equivalent primitives, i.e., Integer to int. This feature was introduced in version 1.5 of java, autoboxing, and unboxing, which are automatic processes handled by JRE; the most important point here is to write proper code that doesn’t add excessive, unnecessary objects in the picture.
How Autoboxing and Unboxing work in Java?
Compiler uses valueOf() method to convert primitives to corresponding wrapper objects (i.e. autoboxing) internally, in the vice versa case it uses intValue(), doubleValue() etc. like paradigms for unboxing.
For reference, the wrapper and primitives mapping in java is mentioned below –
Primitive type | Wrapper class |
boolean | Boolean |
byte | Byte |
char | Character |
float | Float |
int | Integer |
long | Long |
short | Short |
double | Double |
Examples
Let’s take an ArrayList of Integers now and then make use of the unboxing concept.
import java.util.ArrayList;
public class MyClass {
public static void main(String args[]) {
ArrayList<Integer> intlist = new ArrayList<Integer>();
//wrapper Integer objects being added here
intlist.add(1);
interest.add(2);
//auto-unboxing is happening here
int x = intlist.get(0);
System.out.println(x);
}
}
Hence, in the above example, while adding value to x, we see that x appears to be primitive, so unboxing happens here automatically while this assignment is done.
public class MyClass {
public static void main(String args[]) {
Integer sum =0;
for(int i=0;i<10;i++)
{
sum = sum + i;
}
System.out.println(sum);
}
}
- Just above, we have shown an example -2 in this context, where a typical scenario has been presented. If you are acquainted with object creation in java, you can see that “Integer sum =0“, declares an object, and when we do computation inside the for loop, then we can see that primitive value “i” is being added to the wrapper “sum”.
- Hence one can find that first, conversion from wrapper to primitive will occur, as the “+” operator works on primitives only, and hence object unboxing will happen first, then the computation will occur, then object autoboxing will occur back again, and then the value will be assigned to the variable “sum”.
- This presents unnecessary overhead on the JVM as many intermediate Integer objects will be created and will be destroyed (to be later garbage collected), thereby slow down can appear, so such logics shall be handled with care.
- Let’s see now conditions different from general perceptions and will have some code where autoboxing and unboxing get very important to be understood –
Consider the snippet placed below; what do you think will be the output of this?
public class Main
{
public static void main(String[] args) {
Integer m = 34123;
Integer x = 34123;
System.out.println(x==m);
}
}
- If you are saying “true”, then you are “false” because the output is also “false”, it’s because we can compare just the integer range from -128 to 127 like this, for values going out of this range, they are to be unboxed.
- Hence we need to compare intValue() of the above Integers; for now, the compiler makes this done using the valueOf() property.
- Likely, if this falls in the range cited above, then the above code as it is will give true as it will first refer to the integer literal pool for comparison.
public class Main
{
public static void main(String[] args) {
Integer m = 100;
Integer x = 100;
System.out.println(x==m);
}
}
This will evaluate to “true” value, as 100 is present in the literal pool.
Autoboxing and Unboxing in Java with method overloading
- Before we tag autoboxing and unboxing to method overloading, it is assumed that the reader is acquainted with the concept of method overloading; we will just give little insights, and for more, please refer to Oracle’s documentation on the same.
- Method overloading is a process where the same method name is being used with a different number of input arguments, different data types of variables with the same names, etc., use to present multiple variants of any computation method generally.
- Let’s take an example for the same to understand it deeper, and we will also present the output that appears in the picture this time –
public class Main
{
public static void main(String[] args) {
Overload obj = new Overload();
int i =5;
obj.printval(5);
Integer m = i;
obj.printval(m);
}
}
class Overload
{
public void printval(int i)
{
System.out.println("printing the unboxed value "+ i);
}
public void printval(Integer i)
{
System.out.println("printing the autoboxed value "+ i);
}
}
Output:
- Hence the above behavior tells clearly that the autoboxing technique has significant usage in overloading concepts, and it shall be used with care while coding.
Advantages of Autoboxing and Unboxing in Java
- The appropriate conversion is done automatically by the compiler.
- The developer is supposed to write lesser code and thereby cleaner code.
- No need for manual type-casting expressions.
Conclusion
We saw the use-case of autoboxing and unboxing, how implicit this concept is and where it can create pros and cons. It has to be used with care while coding; else, it can add up unnecessary computational conversion overhead; hence conversions shall be done in the primitives to avoid excessive garbage collection overhead and excessive temporary object creation. We also saw the use case of autoboxing with the overload concept of java; you can check a few more constraints along with this.
Recommended Articles
This has been a guide to Autoboxing and Unboxing in Java. Here we also discuss What is Autoboxing and Unboxing in java? how does it work internally with some sample codes? You can also go through our other suggested articles to learn more –
41 Online Courses | 29 Hands-on Projects | 305+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses