Tuesday, August 16, 2011

"==" effect autoboxing in java

Some of the JVM cache objects of some wrapper class e.g. Integer from -128 to 127 and return same object which if compare via “ ==” can return true but after this range this validity doesn’t work and to make it worse this behavior is JVM dependented so better avoid this kind of check and use equals() method.
e.g.

Integer i1 = 260;
Integer i2 = 260;

if (i1 == i2)
System.out.println("i1 and i2 is equal");
else
System.out.println("i1 and i2 is not equal ");

Here you will most probably get "i1 and i2 is not equal " at least in my machine.
because in this case, unboxing operation is not involved. The literal 260 is boxed into two different Integer objects ( again it varies between JVM to JVM) , and then those objects are compared with ==. The result is false, as the two objects are different instances, with different memory addresses. Because both sides of the == expression contain objects, no unboxing occurs.

Integer i1 = 100;
Integer i2 = 100;

if (i1 == i2)
System.out.println("i1 and i2 is equal");
else
System.out.println("i1 and i2 is not equal ");

Here, most probably you will get the text "i1 and i2 is equal".
Because int values from -127 to 127 are in a range which most JVM will like to cache so the VM actually uses the same object instance (and therefore memory address) for both i1 and i2. As a result, == returns a true result.

this is very indeterministic and only shown by example since some JVM do optimization at certain integer value and try to return same object every time but its not guaranteed or written behavior.

So best is to avoid this kind of code in post java 1.5 and instead use equals() method to compare which is more deterministic.

No comments:

Post a Comment