Tuesday, February 12, 2008

Autoboxing and Equality

Tiger(JDK 5) has introduced a lot of features and in turn lots more to dig into. Here I want to explain the issues that arise due to equality comparisons and Autoboxing/Auto-unboxing.

Since, equality operator (==) can be used with reference variables and primitive types, the first question is what happens when we equate reference wrapper variable with its corresponding primitive type.

int i = 1;
Integer iObj = new Integer(i);
System.out.println(i==iObj);


Here, the iObj will be unboxed to a primitive type and the result of the expression would be similar to the comparison of int value with iObj.intValue().

If we equate two reference wrapper variables it is not the value comparisons but object comparison.

Also, JLS recommends that the same wrapper objects should be returned on autoboxing for lower values of the integer primitives. This accounts for some of the unusual behaviour of the equality expressions.

The program and the output below self-explains the issues

package autoboxing;

public class EqualityTest {

public static void main(String[] args) {
// any arbitrary value
int i = 236459;
Integer iObj = new Integer(i);

/*
* if wrapper object is equated with primitive
* types wrapper object would be converted to
* primitive type and then compared
*/

if(i == iObj) {
System.out.println("Integers are equal: " + i);
}

for(int loop = -128; loop < Integer.MAX_VALUE; loop++) {
Integer iObj1 = loop;
Integer iObj2 = loop;

/*
* this is a reference equality check and not value
* comparison
*/
if(iObj1 == iObj2) {

} else {
System.out.println("Integers are not equal: " + loop);
break;
}
}

for(int loop = -128; loop < Integer.MAX_VALUE; loop++) {
Integer iObj1 = new Integer(loop);
Integer iObj2 = new Integer(loop);

/*
* this is a reference equality check and not value
* comparison
*/
if(iObj1 == iObj2) {

} else {
System.out.println("Integers are not equal: " + loop);
break;
}
}
}
}


Output:
Integers are equal: 236459
Integers are not equal: 128
Integers are not equal: -128