4

I have the following code.

public static void doIntCompareProcess() { int a = 100; int b = 100; Integer c = 200; Integer d = 200; int f = 20000; int e = 20000; System.out.println(c == d); compareInt(e, f); compareInt(a, b); } public static void compareInt(Integer v1, Integer v2) { System.out.println(v1 == v2); } 

That gives me this output:

false false true 

Where the currect output should be:

false false false 

Why am I getting the wrong output for the code?

2 Answers 2

11

The last line corresponds to:

compareInt(100, 100); 

Since compareInt() takes two Integer objects, the two parameters get auto-boxed. During that process, instances of Integer(n) for small values of n get interned. In other words, compareInt() receives two references to the same Integer(100) object. This is what's causing the last comparison to evaluate to true.

See Using == operator in Java to compare wrapper objects

The bottom line is to not use the == operator for directly comparing Integer objects. For further discussion, see https://stackoverflow.com/a/1515811/367273

Sign up to request clarification or add additional context in comments.

2 Comments

But the parameter is Integer class
This is a tricky bit, and it's surprising how often we forget about it. Great answer!
4

Integer values in the primitive byte range -128 to 127 are cached for performance reasons. Since 100 is a value in this range, same object from the cache is returned everytime. For values not in this range are believed to be not required frequently and new Integer object is returned for them. Now in your case, you are comparing the object references and not the values and since 100 is coming from the cache, the arguments in compareInt() are pointing to the same object and hence the comparison equates to true.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.