Autoboxing and unboxing conversions in Java

UPDATED: 08 January 2017
Autoboxing and unboxing in java

Autoboxing and Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called Unboxing.

Autoboxing
Converting primitive values (int, long, float, double...) into an object of the corresponding wrapper class (Integer, Long, Float, Double...) is called autoboxing. The compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Autoboxing Example
The given code
/* Passed as a parameter to a method that expects an object of the corresponding wrapper class. */
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(i); 
}
=====
/* Assigned to a variable of the corresponding wrapper class. */
int x = 10;
Integer y = x;
will be converted by compiler as follow, Here i is autoboxed by Integer.valueOf(i).
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(Integer.valueOf(i));
}
=====
int x = 10;
Integer y = Interger.valueOf(x);

Unboxing
Converting an object of a wrapper type (Integer, Long, Float, Double...) to its corresponding primitive (int, long, float, double...) value is called unboxing. The compilere applied unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Unboxing Example
The given code
/* Assigned to a variable of the corresponding primitive type. */
int sum = 0;
for (Integer i : listIntegers){
 if (i % 2 == 0){
  sum += i;
 }    
}
=====
/* Passed as a parameter to a method that expects a value of the corresponding primitive type. */
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a, b);

public int sum(int x, int y){
  return x + y;
}
will be converted by compiler as follow because remainder (%) and unary plus (+=) don't apply on wrapper class Integer. Here i % 2 unboxed by i.intValue() % 2 and sum += i unboxed by sum += i.intValue().
int sum = 0;
for (Integer i : listIntegers){
 if (i.intValue() % 2 == 0){
  sum += i.intValue();
 }    
}
=====
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a.intValue(), b.intValue());

public int sum(int x, int y){
  return x + y;
}

0 comments :