I had the same question a couple of days ago. Now I solved it. I think the output will be like this (I didn't run through JVM though, point me out if I am wrong): i1!=i2 i1 equals i2 i3==i4 i3 equals i4
the trick is that autoboxing gives you same object if the date range is from -128 to 127 any integer type wrapper classes.
The code demonstrates the usage of autoboxing and unboxing feature and the equality of two objects or two primitives.
Autobxing & unboxing is the new feature introduced in Java Tiger to automatically convert primitives into respective wrapper object/object to primitive type.
The primitives are equal and the values of the boxed ints are equal in the case of small integral values [-128, 127], . In this case the objects are cached in a pool much like Strings. When i3 and i4 are 24, a single object is referenced from two different locations.
But i1 and i2 are 1001, two separate objects are referenced. Autoboxing is guaranteed to return the same object for integral values in the range [-128, 127], but an implementation may, at its discretion, cache values outside of that range.
Note: You need JDK 1.5 or higher to run the code.
Hence the code flow is..
Integer i1 = 1001; // 1001 int primitive autoboxed to Integer object i1 Integer i2 = 1001; // 1001 int primitive autoboxed to Integer object i2
Integer i3 = 24; // 24 int primitive autoboxed to Integer object i3 Integer i4 = 24; // 24 int primitive autoboxed to Integer object i4
if(i1 == i2) System.out.println("i1==i2"); // object i1 compared with object i2 by == returns false
if(i1 != i2) System.out.println("i1!=i2"); // object i1 compared with object i2 by == returns false
if(i1.equals(i2)) System.out.println("i1 equals i2"); // object i1 compared with object i2 by Object.equals(Object) returns true