Wednesday, August 26, 2009

[Java] Boxing, ==, and equals() tweak

It shouldn't be surprising that

Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

Produces the output:

different objects
meaningfully equal

How about this one:

Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");

This example produces the output:

same object
meaningfully equal

Yikes! The equals() method seems to be working, but what happened with == and != ? Why is != telling us that i1 and i2 are different objects, when == is saying that i3 and i4 are the same object? In order to save memory, two instances of the following wrapper objects (created through boxing), will always be == when their primitive values are the same:
■ Boolean
■ Byte
■ Character from \u0000 to \u007f (7f is 127 in decimal)
■ Short and Integer from -128 to 127


Source: Sierra & Bates SCJP 6 Study Guide , Chapter 3

2 comments:

Richard Berger said...

Hey, I was just reading this chapter in the SCJP study guide and thought I would write some variants of the code as test.

But what I don't get is the following test case:

public class Test {
public static void main (String[] args) {
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);

Integer i3 = 10;
Integer i4 = 10;

if (i1 == i2) {
System.out.println("i1, i2 are ==");
}
if (i1 != i2) {
System.out.println("i1, i2 are !=");
}

if (i3 == i4) {
System.out.println("i3, i4 are ==");
}
if (i3 != i4) {
System.out.println("i3, i4 are !=");
}
}
}

i1 and i2 are clearly objects and when compared with == use identity compare and thus are !=.

According to the example in the book, i3 and i4 should be != , but my output does NOT show this. When I run the above, I get:

i1, i2 are !=
i3, i4 are ==

Can you see what I am doing wrong? Or can you try this code? My environment may be 6.0 rather than 5.0, I wonder if that is the issue.

Thanks so much!
Richard

richardlandis@gmail.com

Richard Berger said...

OK, I figured it out. If I change the 10 to 1000, it works as expected. Reading further in the text explains that Integers from negative 127 to positive 128 are treated differently than Integers higher than 128