Java has eight primitive data types i.e. int, double, etc. Many collections and other Java objects cannot handle primitives so they need to be converted to objects. So each primitive type has a wrapper class defined. Integer for int, Double for double, and so on. In addition to enabling primitives to be used by objects that do not support primitives, wrapper classes also provide many useful functions for manipulation of the data represented in the wrapper object.
Following is a table of primitives and their wrapper classes:
byte Byte short Short int Integer long Long float Float double Double char Char boolean Boolean
Converting a primitive to wrapper object in called boxing.
Converting a wrapper object to a primitive is called unboxing.
Java automatically boxes primitives and unboxes wrapper objects. This is called autoboxing and auto-unboxing.
import java.util.ArrayList;
public class Boxing {
public static void main(String[] args) {
// variable declaration
int a = 1;
Integer c = 3;
ArrayList e = new ArrayList();
// manual unboxing
a = new Integer(4);
System.out.println(a);
// auto-unboxing
a = c;
System.out.println(a);
a = 100;
// manual boxing
Integer d = new Integer(a);
System.out.println(d);
// autoboxing
d = 50;
System.out.println(d);
// autoboxing in ArrayList
e.add(d); // adding an Integer
e.add(3); // adding an int
System.out.println(e.get(0));
System.out.println(e.get(1));
}
}
Output
4
3
100
50
50
3