Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does comparing Integers with == do?

EDIT: OK, OK, I misread. I'm not comparing an int to an Integer. Duly noted.

My SCJP book says:

When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.

So you'd think this code would print true:

    Integer i1 = 1; //if this were int it'd be correct and behave as the book says.
    Integer i2 = new Integer(1);
    System.out.println(i1 == i2);

but it prints false.

Also, according to my book, this should print true:

Integer i1 = 1000; //it does print `true` with i1 = 1000, but not i1 = 1, and one of the answers explained why.
Integer i2 = 1000;
System.out.println(i1 != i2);

Nope. It's false.

What gives?

like image 880
Bad Request Avatar asked Sep 11 '10 03:09

Bad Request


2 Answers

Note also that newer versions of Java cache Integers in the -128 to 127 range (256 values), meaning that:

Integer i1, i2;

i1 = 127;
i2 = 127;
System.out.println(i1 == i2);

i1 = 128;
i2 = 128;
System.out.println(i1 == i2);

Will print true and false. (see it on ideone)

Moral: To avoid problems, always use .equals() when comparing two objects.

You can rely on unboxing when you are using == to compare a wrapped primitive to a primitive (eg: Integer with int), but if you are comparing two Integers with == that will fail for the reasons @dan04 explained.

like image 52
NullUserException Avatar answered Sep 20 '22 20:09

NullUserException


Integer i1 = 1;
Integer i2 = new Integer(1);
System.out.println(i1 == i2);

When you assign 1 to i1 that value is boxed, creating an Integer object. The comparison then compares the two object references. The references are unequal, so the comparison fails.

Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1 != i2);

Because these are initialized with compile-time constants the compiler can and does intern them and makes both point to the same Integer object.

(Note that I changed the values from 1000 to 100. As @NullUserException points out, only small integers are interned.)


Here's a really interesting test. See if you can figure this out. Why does the first program print true, but the second one false? Using your knowledge of boxing and compiler time analysis you should be able to figure this out:

// Prints "true".
int i1 = 1;
Integer i2 = new Integer(i1);
System.out.println(i1 == i2);

// Prints "false".
int i1 = 0;
Integer i2 = new Integer(i1);
i1 += 1;
System.out.println(i1 == i2);

If you understand the above, try to predict what this program prints:

int i1 = 0;
i1 += 1;
Integer i2 = new Integer(i1);
System.out.println(i1 == i2);

(After you guess, run it and see!)

like image 44
John Kugelman Avatar answered Sep 22 '22 20:09

John Kugelman