First look at what the following code will output:
public static void Main (string[] args) {
Integer i = 127;
Integer j = 128;
Integer II = 127;
Integer JJ = 128;
System.out.println (I==II);
System.out.println (J==JJ);
}
The answer is: true,false
What is this for? The reason is that the boxing action is achieved through the valueof method,
The object pool is used in the ValueOf method. If the parameter is between -128~127, the
The object is obtained directly from the object pool, not within that range, and the wrapper object is generated through new.
Let's take a look at the source code:
public static Integer valueOf (int i) {
Assert Integercache.high >= 127;
if (i >= integercache.low && i <= integercache.high)
low=-128,high=127
return integercache.cache[i + (-integercache.low)];
return new Integer (i);
}
So why can't you see the boxing action? How do you know it must be called the valueof function?
Automatic Boxing is the compilation of its behavior. We can compile the code and decompile it to see what the JVM directive is.
Here is the partially deserialized code in the above example:
Compiled from "Integertest.java"
public class Test.integertest {
public Test.integertest ();
Code:
0:aload_0
1:invokespecial #1//Method java/lang/object. " <init> ":() V
4:return
public static void Main (java.lang.string[]);
Code:
0:bipush 127
2:invokestatic #2//Method java/lang/integer.valueof: (I) Ljava/lang/integer;
5:astore_1
6:sipush 128
9:invokestatic #2//Method java/lang/integer.valueof: (I) Ljava/lang/integer;
}
We can see that auto boxing is really called the valueof function.
Integer Auto-boxing analysis