Thursday, September 25, 2014

Autoboxing and Unboxing in Java



Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. If the conversion goes the other way, this is called unboxing


Autoboxing

Character ch = 'a';
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(i); //it creates an Integer object from i and adds the object to li.
 ******************
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(Integer.valueOf(i)); // compiler converts the previous code to the following at runtime
unboxing
Integer i = new Integer(-8);

        // Unboxing through method invocation

        int absVal = absoluteValue(i);



List<Double> ld = new ArrayList<>();

        ld.add(3.1416);    // autoboxed through method invocation.

        // Unboxing through assignment

        double pi = ld.get(0);

Primitive type
Wrapper class
boolean
Boolean
byte
Byte
char
Character
float
Float
int
Integer
long
Long
short
Short
double
Double

Benefits of Autoboxing / Unboxing

  • Autoboxing / Unboxing lets us use primitive types and Wrapper class objects interchangeably.
  • We don't have to perform explicit typecasting
  • It helps prevent errors, but may lead to unexpected results sometimes. Hence must be used with care.

No comments:

Post a Comment