Integer construction variations
Asked Answered
I

2

2

Hey all, I ran into an interesting occurrence and am looking for an explanation.

In Java 1.6:

Integer a = new Integer(5);
Integer b = new Integer(5);

System.out.println(a == b);

Integer c = 5;
Integer d = 5;

System.out.println(c == d);

I get:

false
true

In Eclipse I checked in the debugger. a and b are different objects, while c and d are the same objects (but different from a and b).

Can anyone clue me in on what's going on under the hood? Is this JVM magic? Realizing that a Integer(5) is already on the stack?

Insignia answered 3/5, 2011 at 4:36 Comment(0)
A
6

Java caches Integer instances for values it deems close enough to zero if they're constants. Manually creating an Integer using new bypasses that cache. You can call Integer.valueOf with an int to get the corresponding Integer without bypassing the cache.

You may want to search for "JVM Integer cache" on your search engine of choice for more information.

Abeokuta answered 3/5, 2011 at 4:38 Comment(5)
I believe all values from -128 to 127 are cached, and i'm pretty sure it was for Sun's JVM.Ingmar
See also Integer.valueOf(int i)Moldboard
in addition, the jvm is allowed to cache integers fetched thru Integer.valueOf, so you may get the same object back for two calls to Integer.valueOf even if the number is outside the -128-127 range.Mouthwatering
Interesting related read, thecodersbreakfast.net/index.php?post/2011/04/13/Java-Quiz-44Assamese
Huh. That is fancy. I figured new forced the object creation but was confused as to how Java/JVM resolved the other instances. Thanks all.Insignia
P
1

@icktoofay's answer nails it, but the comments are muddying the waters.

  • The JLS edition 3.0 requires that integers in the ranges -128 to +127 are autoboxed to cached values; see JLS section 5.1.7. In other words, you can rely on this behaviour for integers in that range, for all complaint Java 5 and later platforms.

    (Similar requirements apply to booleans, bytes, chars and shorts.)

  • The JLS specifically allows the same autoboxing behaviour to extend across a wider range of values.

Phyllotaxis answered 3/5, 2011 at 5:10 Comment(1)
Ah, I see. I was aware of the autoboxing, but didn't realize that cached values were implicated. Very neat little thing.Insignia

© 2022 - 2024 — McMap. All rights reserved.