A concept,

Autoboxing refers to the Java compiler automatically converting primitive types to their corresponding Object wrapper classes. For example, int->Integer, double-> double, if it’s the other way around, it’s called Unboxing.

Two, automatic packing

1. Case driven

Let’s take a look at this case:

List<Integer> list = new ArrayList<>();
for(int i = 0; i<50; i+=2)
    list.add(i);
Copy the code

We define an Arraylist whose generic type is Integer. According to the generics principle, when we add data, we should only add objects of type Integer. Adding basic data types will cause a compilation error, but in this case the compiler did not report an error.

2. Cause analysis

The reason for this error is that the Java compiler creates an object of type Integer corresponding to data of type int. The compiler converts the case code to the following code at run time:

List<Integer> list = new ArrayList<>();
for(int i = 0; i<50; i+=2)
    list.add(Integer.valueOf(i));
Copy the code

We can also decompile the example code as follows:

D:\IdeaProjects\HighJava\out\production\practice\BoxandUnbox>javap -c AutoBoxing.class Compiled from "AutoBoxing.java" public class BoxandUnbox.AutoBoxing { public BoxandUnbox.AutoBoxing(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: new #2 // class java/util/ArrayList 3: dup 4: invokespecial #3 // Method java/util/ArrayList."<init>":()V 7: astore_1 8: aload_1 9: iconst_1 10: invokestatic #4 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 13: invokevirtual #5 // Method java/util/ArrayList.add:(Ljava/lang/Object;) Z 16: pop 17: return }Copy the code

As you can see, the static method valueOf() of Integer is actually called at run time in Code10 of the main method.

Three, automatic unpacking

The principle of automatic unboxing is similar to that of automatic boxing. In essence, the compiler automatically calls the intValue() method of Integer at runtime, which will not be described here.

Four,

1. Automatic packing

  • When a primitive type is passed as an argument to a method that needs its corresponding wrapper class object;
  • A variable assigned to its corresponding wrapper class object

2. Automatic unpacking

  • When a wrapper class object is passed as a parameter to a method that needs its corresponding primitive type;
  • A variable assigned to its corresponding primitive type

Four, additional

The following table shows the data types that the Java compiler can unpack and their corresponding wrapper classes:

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