English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java Auto装箱和拆箱 (Auto-boxing and Unboxing)

In this tutorial, we will learn about Java automatic boxing and unboxing with examples.

Java automatic boxing-The original type of the wrapper object

InAutomatic boxing inThe Java compiler will automatically convert the primitive type to its corresponding wrapper class object. For example,

int a = 56;
// Auto-boxing
Integer aObj = a;

When using Java collections,Auto-boxinghas a great advantage.

Example1: Java automatic boxing

import java.util.ArrayList;
class Main {
   public static void main(String[] args) {
      ArrayList<Integer> list = new ArrayList<>();
      //Auto-boxing
      list.add(5);
      list.add(6);
      System.out.println("ArrayList: " + list);
   }
}

Output Result

ArrayList: [5, 6]

In the above example, we created an array list of Integer type. Therefore, the array list can only contain Integer objects.

Note this line,

list.add(5);

Here, we pass the primitive type value. However, sinceAuto-boxing, the primitive values will be automatically converted to Integer objects and stored in the array list.

Java unboxing-Wrapper objects for primitive types

InUnboxing inThe Java compiler will automatically convert the wrapper class object to its corresponding primitive type. For example,

// Auto-boxing
Integer aObj = 56;
// Unboxing
int a = aObj;

LikeAutomaticBoxingLikeUnboxingCan also be used with Java collections.

Example2:Java Unboxing

import java.util.ArrayList;
class Main {
   public static void main(String[] args) {
      ArrayList<Integer> list = new ArrayList<>();
      //Auto-boxing
      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 Result

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

In the above example, please note the following line:

int a = list.get(0);

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