Autoboxing and Unboxing
The Autoboxing and Unboxing was released with the Java 5.
Autoboxing
During assignment, the automatic transformation of primitive type(int, float, double etc.) into their object equivalents or wrapper type(Integer, Float, Double,etc) is known as Autoboxing.
During assignment or calling of constructor, the automatic transformation of wrapper types into their primitive equivalent is known as Unboxing.
Conversion of int into Integer
int inative = 0; inative = new Integer(5); // auto-unboxing Integer intObject = 5; // autoboxing
Storing int a into vector vt
int a = 10; Vector <integer> vt = new Vector <integer> (); vt.add(a); int n = vt.elementAt(0); </integer></integer>
Autoboxing also works with comparison
int a = 10; Integer b = 10; System.out.println(a==b);
Output of the above code will be :
Output :
true |
EXAMPLE
Boxing/Unboxing of Character value :
public class MainClass { public static void main(String args[]) { Boolean booleanObject = true; if (booleanObject){ System.out.println("b is true"); } Character ch = 'x'; // box a char char ch2 = ch; // unbox a char System.out.println("ch2 is " + ch2); } }
Output
b is true
ch2 is x |