Java autoboxing and unboxing

Java Autoboxing - Primitive Type to Wrapper Object

In autoboxing, the Java compiler automatically converts primitive types into their corresponding wrapper class objects. For example,

int a = 56;

// autoboxing
Integer aObj = a;

Autoboxing has a great advantage while working with Java collections.


Example 1: Java Autoboxing

import java.util.ArrayList;

class Main {
   public static void main(String[] args) {

      ArrayList<Integer> list = new ArrayList<>();

      //autoboxing
      list.add(5);
      list.add(6);

      System.out.println("ArrayList: " + list);
   }
}

Output

ArrayList: [5, 6]

In the above example, we have created an array list of Integer type. Hence the array list can only hold objects of Integer type.

Notice the line,

list.add(5);

Here, we are passing primitive type value. However, due to autoboxing, the primitive value is automatically converted into an Integer object and stored in the array list.


Java Unboxing - Wrapper Objects to Primitive Types

In unboxing, the Java compiler automatically converts wrapper class objects into their corresponding primitive types. For example,

// autoboxing
Integer aObj = 56;

// unboxing
int a = aObj;

Like autoboxing, unboxing can also be used with Java collections.


Example 2: Java Unboxing

import java.util.ArrayList;

class Main {
   public static void main(String[] args) {

      ArrayList<Integer> list = new ArrayList<>();

      //autoboxing
      list.add(5);
      list.add(6);

      System.out.println("ArrayList: " + list);

      // unboxing
      int a = list.get(0);
      System.out.println("Value at index 0: " + a);
   }
}

Output

ArrayList: [5, 6]
Value at index 0: 5

In the above example, notice the line,

int a = list.get(0);

Here, the get() method returns the object at index 0. However, due to unboxing, the object is automatically converted into the primitive type int and assigned to the variable a.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges