First look at the code
Why 100 is equal, but 200 is not equal, after reading the above results, do you have this question, then Xiaobai will take everyone to understand
First of all, we need to know, what is the reference data type ==?
The reference data type actually exists in the heap memory, and the == comparison is actually its memory address
Then let's find out
Let's take a look at the bytecode instructions of the code, let's just say one, and the others are similar
When we execute Integer intA = 100;, the JVM executes 3 instructions, which means first load a constant of 100, call the valueOf method of Integer, and store the result in the second slot of the local variable table (note the return value is an Integer, the result is the address of the reference data type, not the real value), then the focus shifts to the Integer.valueOf() method, let’s take a look
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
The above is the source code of Integer.valueOf(). First, it is a judgment. If i is between low and high, call IntegerCache.cache() to return, otherwise new Integer()
Then let's take a look at what low and high are?
Two static variables, although high has no explicit assignment, but they are assigned in the static inner class, they are -128, 127, which happens to be one of our 100 and 200, and one is not, then let's look at IntegerCache.cache() what is it
Look here, cache is a static variable, array type, it has been assigned when the class is loaded, the length is 256, and the value is -128-127 through loop assignment, which can be understood as a cache
Then let's reinterpret here, if the value of i is between -128-127, get it directly from the cache, otherwise new Integer()
Then the values of intA and intB are 100, they are actually the values in the cache, they are the same address, so they are equal
The values of intC and intD are 200, and two Integers are renew, the addresses must be different
epilogue
1. It's not easy to make, let's go with one click and three consecutive times. Your support will always be my biggest motivation!
2. Java full-stack technology exchange Q group: 941095490, welcome to join!