Autoboxing and Unboxing in Java

Autoboxing and Unboxing convert primitive types to corresponding Wrapper classes and vice versa. In Java, all primitive data types have a corresponding Wrapper class. Wrapper classes provide a way to use primitive data types as objects.

Converting a primitive type to a Wrapper class is called autoboxing, and converting a wrapper class to a primitive type is known as unboxing.

A table of primitive types and their corresponding Wrapper classes:

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

Java Autoboxing – Primitive Type to Wrapper Class

In the case of autoboxing, the Java compiler will automatically convert the primitive type to the appropriate Wrapper class.

Example 1:

class Test {
    
  int id = 5;
  Integer id1 = id; // autoboxing
}

Autoboxing is very useful when working with lists since lists do not work with primitive types.

Example 2:

class Test {
    
  public static void main(String[] args) {
    int a = 10;
    int b = 20;
    
    List<Integer> list = new ArrayList();
    list.add(a); //autoboxing 
    list.add(b); // autoboxing
    list.add(30);
  }
}

Here we have a list of objects of the Integer class. We add elements of the primitive type, and automatic autoboxing happens.

Another example would be when we have a method that accepts a Character object as a parameter. We can pass it a value of primitive type char, like in the following example.

Example 3:

class Test {
    
  public void printCharacter(Character character) {
    System.out.println("Character: " + character);
  }
    
  public static void main(String[] args) {
    Test test = new Test();
    char ch = 'c';
    test.printCharacter(ch);
  }
}
Output: Character: c
 

Java Unboxing – Wrapper Objects to Primitive Types

In the case of unboxing, the Java compiler will convert the object of the Wrapper class into the primitive type.

Example 1:

class Test {
    
  Integer id = 10;
  int id1 = id; // unboxing
}

Also, we can pass an appropriate wrapper object to a method that expects a primitive type.

Example 2:

class Test {
    
  public void printDouble(double d) {
    System.out.println("Double value: " + d);
  }
    
  public static void main(String[] args) {
    Test test = new Test();
    Double d = 5.2;
    test.printDouble(d);
  }
}
Output: Double value: 5.2


That was all regarding Autoboxing and Unboxing in Java!

Leave a Reply

Your email address will not be published.