AutoBoxing And UnBoxing

AutoBoxing

When we convert primitive data type to wrapper class object it is called AutoBoxing. It is done by Java compiler while we are assigning primitive value to wrapper class object.

 Integer a = 10; //Java compiler automatically converts primitive value to wrapper class object
 List<Integer> list = new ArrayList<Integer>();
 for(int i=1;i<=10;i++){
   list.add(i); //Java compiler automatically converts i to wrapper object
 }

Wrapper Class Caching

To save memory and improve performance caching was introduced in Java 5. Object creation really expensive process.

Caching will be done during wrapper class loading and keep cached objects in pool for some range of values and return the reference of cached object if value is between the range. Wrapper class caching only works with autoboxing.

Integer Class Caching

Java provides caching mechanism for Integer class where values range between -128 to 127 is being cached in memory. Same references are being share while autoboxing.

Example

Both x1 and x2 will get same reference due to caching while autoboxing. But x3 will get new instance with difference reference.

public class IntegerCachingExample{
 
    public static void main(String[] args) {
        Integer x1 = 100;  
        Integer x2 = 100;
        Integer x3 = new Integer(100);

        System.out.println(x1 == x2);
        System.out.println(x1 == x3);
    }
}

Other Wrapper Class caching

  1. Boolean class store two inbuilt instances TRUE and FALSE, and return their reference if new keyword is not used.
  2. Character class has a cache for chars between unicodes 0 and 127 (ascii-7 / us-ascii).
  3. Long class has a cache for long between -128 to +127.

Output

 
true 
false 

UnBoxing

When wrapper class object is converted to primitive one then it is called Unboxing. It is done by compiler itself while are assign wrapper object to primitive data type variable.

public class Unboxing{ 
public static void main(String[] args) {
 Integer x1 = 100; //autoboxing
 int x2 = x1;//unboxing
 } 
}

How many objects will be created for following

public class WrapperTest{
 public static void main(String args[]){
 Integer a=10;
 Integer b=10;
 Integer c= new Integer(10);
 Integer d = c;
 }
}

Output

 3

What is output of the following

 public class WrapperTest{
  public static void main(String args[]){
   Integer a=10;
   Integer b=10;
   Integer c= new Integer(10);
   Integer d = c;
   Integer e = null;
   System.out.println(a==b);
   System.out.println(b=e=c);
   System.out.println(d==e);
 }
 }

Output

 true
 10
 true

Leave a Reply