4

Possible Duplicate:
Wrapper class and == operator

It seems as if object equality operator for wrapper classes produces different results depending on whether the wrapped value is in byte range or not. Here is a code snippet to demonstrate this behavior:

System.out.println("smaller than byte");

Integer i1 = 1;

Integer i2 = 1;

if (i1 == i2) System.out.println("same");

if (i1 != i2) System.out.println("not same");

System.out.println("larger than byte");

Integer i3 = 128;

Integer i4 = 128;

if (i3 == i4) System.out.println("same");

if (i3 != i4) System.out.println("not same");

produces the following output:

smaller than byte

same

larger than byte 

not same

Note: I got this output on HotSpot (build 1.6.0_24-b07) on linux. Same happens for Long and probably Short (haven't tested it though).

Note: Same output on other HotSpot builds under linux Can anyone explain it?


Small edit, just to make it slightly more interesting:

Adding

if (i3 <= i4 && i3 >= i4) System.out.println("same after all...");

in the end, prints "same after all...".

Community
  • 1
  • 1
maciek
  • 49
  • 2

2 Answers2

4

That's correct. The JVM will "cache" and reuse Integer instances when autoboxing small values.

See Java Language Specification Section 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.

When comparing Integers using <, >, <= and >= the values are un-boxed as opposed to != and ==.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • thanks - I'm currently learning for SCJP and found a similar example in the official study guide - the explanation the authors give for this behavior is different ( and obviously wrong!) – maciek Aug 02 '11 at 11:48
  • @maciek: really? Could you tell us which source you think is wrong or even give a short excerpt? – Joachim Sauer Aug 02 '11 at 12:07
  • well, i haven't read it carefully enough as it seems. it actually says further in the text that this behavior applies to Short and Integer only between -128 and 127. my fault – maciek Aug 02 '11 at 15:59
2

Integers between -127 and 127 are 'cached', so they return same reference, which means i1 and i2 point to same object.

Aniruddha
  • 3,513
  • 6
  • 27
  • 38