Autoboxing and Unboxing in Java
In java, all the primitive data types have defined using the class concept, these classes known as wrapper classes. In java, every primitive type has its corresponding wrapper class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper class.
S.No. | Primitive Type | Wrapper class |
---|---|---|
1 |
byte |
Byte |
2 |
short |
Short |
3 |
int |
Interger |
4 |
long |
Long |
5 |
float |
Float |
6 |
double |
Double |
7 |
char |
Character |
8 |
boolean |
Boolean |
The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper type and reverses of it.
Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper class object is called autoboxing or simply boxing. For example, converting an int value to an Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has assigned to an object of the corresponding wrapper class.
🔔 We can also perform autoboxing manually using the method valueOf( ), which is provided by every wrapper class.
Let's look at the following example program for autoboxing.
import java.lang.*;
public class AutoBoxingExample {
public static void main(String[] args) {
// Auto boxing : primitive to Wrapper
int num = 100;
Integer i = num;
Integer j = Integer.valueOf(num);
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}
Auto un-boxing in Java
In java, the process of converting an object of a wrapper class type to a primitive type value is called auto un-boxing or simply unboxing. For example, converting an Integer object to an int value.
The compiler automatically performs the auto un-boxing when a wrapper class object has assigned to aprimitive type.
🔔 We can also perform auto un-boxing manually using the method intValue( ), which is provided by Integer wrapper class. Similarly every wrapper class has a method for auto un-boxing.
Let's look at the following example program for autoboxing.
import java.lang.*;
public class AutoUnboxingExample {
public static void main(String[] args) {
// Auto un-boxing : Wrapper to primitive
Integer num = 200;
int i = num;
int j = num.intValue();
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}