Integer i = 5;
Integer j = 5;
if (i == j) System.out.println("true");

^ Prints true

Integer i = new Integer(5);
Integer j = new Integer(5);
if (i == j) System.out.println("true");

^ Does not print true.

I understand that in the second case, the == is comparing the references. But why not in the first case? It almost seems like the compiler is treating it as two 'ints' in the first case, since it knows in advance from the declaration. But shouldn't it be autoboxed as an Integer? Thanks

Edited by BestJewSinceJC: n/a

8 Years
Discussion Span
Last Post by BestJewSinceJC

Because Integers are final, and can't change, maybe the compiler optimises by creating one Integer(5) and pointing both refs at it (like Strings). ? ???


I knew I'd seen this before...

Autoboxing uses Integer.valueOf, which internally caches Integer objects for small integers (by default -128 to 127, but the max value can be configured with the "java.lang.Integer.IntegerCache.high" property - see the source code of Integer.valueOf), so it is different from calling new Integer directly.

Votes + Comments
good post

Good example of a potential problem with Autoboxing. i and j are objects but the compiler allows you to use them like primitives, EXCEPT for your example.

BTW I don't care for compilers hiding things like this to save a few key strokes.


Very useful link s.o.s. and thanks everyone for the replies. To summarize (for anyone who comes to this thread at a later date) I tested the theory of s.o.s's link by using

Integer i = 127;
Integer j = 127;
if (i == j) System.out.println("true");

And it prints true, but

Integer i = 128;
Integer j = 128;
if (i == j) System.out.println("true");

Does not print true.

I think it is true that the Java specification does *not* say that the references can't be the same when the primitive value is 128, just that it *has to be* the same if the primitive value is 127 (or any of the other values mentioned in that link). By the way, going back to my first post, if you explicitly create a new Integer Object, then obviously, the references won't be the same.

Thanks again guys

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.