Java Integer Memory Allocation

Hi, I am trying to understand the following piece of code.

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 executes all println instructions. That is, i1! = I2 is true, but i3 == i4. At first glance this seems strange to me, they should be different as links. I can understand that if I pass the same byte value (from -128 to 127) to i3 and i4, they will always be equal as links, but any other value will give them as different.

I can’t explain this, can you point me to some documentation or provide useful information?

thanks

+6
java memory integer
source share
3 answers

Autoboxing int values ​​for Integer objects will use the cache for shared values ​​(as you identified them). This is indicated in JLS in Β§5.1.7. Boxing Conversion :

If the value of p in the box is true , false , a byte , a char in the range from \u0000 to \u007f or the number int or short between -128 and 127 , then let r1 and r2 be the result of any two transformations of the box into p . It always happens that r1 == r2.

Please note that this will only happen if the language automatically sets a value for you or when you use Integer.valueOf() . Using new Integer(int) will always create a new Integer object.

A slight hint: The JVM implementation may also cache values ​​outside of these ranges because the opposite is not indicated. However, I have not seen such an implementation.

+12
source share

Java stores the Integer pool between -128 and 128. If you use Integer outside this range, new Integer objects are created. This is an explanation.

Here you can see it in the Java source code:

 public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); } 
+2
source share

Integers from -128 to 127 are wrapped in fixed objects. That is why you get i3 == i4.

+1
source share

All Articles