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
if(i3 == i4) System.out.println("i3==i4"); // returns true (int within range [-128, 127] )
if(i3 != i4) System.out.println("i3!=i4"); // returns false
if(i3.equals(i4)) System.out.println("i3 equals i4"); // returns true
[ October 07, 2006: Message edited by: rajeswari kannan ]