Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer memory allocation

Hey I am trying to understand 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 of the println instructions. That is i1 != i2 is true, but i3 == i4. At first glance this strikes me as strange, they should be all different as references. I can figure out that if I pass the same byte value (-128 to 127) to i3 and i4 they will be always equal as references, but any other value will yield them as different.

I can't explain this, can you point me to some documentation or give some helpful insights?

Thank you

like image 288
Victor Blaga Avatar asked Mar 16 '11 10:03

Victor Blaga


3 Answers

Autoboxing int values to Integer objects will use a cache for common values (as you've identified them). This is specified in the JLS at §5.1.7 Boxing Conversion:

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Note that this will only be applied when the language auto-boxes a value for you or when you use Integer.valueOf(). Using new Integer(int) will always produce a new Integer object.

Minor hint: a JVM implementation is free to cache values outside of those ranges as well, because the opposite is not specified. I've not yet seen such an implementation, however.

like image 122
Joachim Sauer Avatar answered Nov 14 '22 17:11

Joachim Sauer


Java keeps a pool of Integer between -128 and 128. If you use Integer outside of this range, new Integer objects are created. That's the 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);
    }
like image 20
RoflcoptrException Avatar answered Nov 14 '22 16:11

RoflcoptrException


Integers from -128 to 127 are wrapped into fixed objects. That's why you get i3 == i4.

like image 29
Grzegorz Szpetkowski Avatar answered Nov 14 '22 18:11

Grzegorz Szpetkowski