Breaking News
yeni film izle hd film seyret film izle

Autoboxing and Unboxing In Java

Autoboxing and Unboxing

  • Autoboxing and Unboxing features was added in Java5.
  • Autoboxing is a process by which primitive type is automatically encapsulated(boxed) into its equivalent type wrapper
  • Auto-Unboxing is a process by which the value of object is automatically extracted from a type wrapper.

Example of Autoboxing and Unboxing

class Test
{
 public static void main(String[] args)
 {
  Integer iob = 100;      //Autoboxing of int
  int i = iob;          //unboxing of Integer
  System.out.println(i+" "+iob);

  Character cob = 'a';       /Autoboxing of char
  char ch = cob;            //Auto-unboxing of Character
  System.out.println(cob+" "+ch);
 }
}

Output :

100 100
a a

Autoboxing / Unboxing in Expressions

Whenever we use object of Wrapper class in an expression, automatic unboxing and boxing is done by JVM.

Integer iOb;
iOb = 100;        //Autoboxing of int
++iOb;

When we perform increment operation on Integer object, it is first unboxed, then incremented and then again reboxed into Integer type object.

This will happen always, when we will use Wrapper class objects in expressions or conditions etc.


Benefits of Autoboxing / Unboxing

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

 

Check Also

StringBuilder class

StringBuilder class StringBuilder is identical to StringBuffer except for one important difference it is not …