Java integer memory allocation
Hey, I want to know the following code snippet
public static void main(String[] args) { Integer i1 = 1000; Integer i2 = 1000; if(i1 != i2) System.out.println("different objects"); if(i1.equals(i2)) System.out.println("meaningfully equal"); Integer i3 = 10; Integer i4 = 10; if(i3 == i4) System.out.println("same object"); if(i3.equals(i4)) System.out.println("meaningfully equal"); }
This method runs all println instructions That's I1= I2 is true, but I3 = = I4 At first glance, it seems strange to me that they should be different references I can make it clear that if I pass the same byte values (- 128 to 127) to I3 and I4, they will always be equal to the reference, but any other value will make them different
I can't explain this. Can you point out some documents or provide some useful insights?
thank you
Solution
Auto boxing int values into integer objects uses the cache to get commonly used values (because you already recognize them) This is in JLS at § 5.1 7 specified in boxing conversion:
Note that only if the language automatically sets values for you or uses integer This option applies only when valueof() Using new integer (int) always generates a new integer object
Secondary tip: JVM implementations are also free to cache values outside these ranges because no opposite value is specified However, I haven't seen such an implementation yet