type wrapper

Java uses primitive types such as int, double or float to hold the basic data types for the sake of performance. Despite the performance benefits offered by the primitive types, there are situation when you will need an object representation. For example, many data structures in Java operate on objects, so you cannot use primitive types with those data structures. To handle these situations Java provides type Wrappers which provide classes that encapsulate a primitive type within an object.

  • Character : It encapsulates primitive type char within object.
    Character (char ch)
    
  • Boolean : It encapsulates primitive type boolean within object.
    Boolean (boolean boolValue)
    
  • Numeric type wrappers : It is the most commonly used type wrapper.
    Byte Short Integer Long Float Double

    Above mentioned Classes comes under Numeric type wrapper. These classes encapsulate byte, short, int, long, float, double primitive type.


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.