Comparing Integer in Java -autoboxing does not apply there

Hmm.. it came as most basic surprise for me, I wrote


where questionid is of type Integer (Object and not primitive).

Logically, it’s a reference comparison and should fail, but since its a wrapper for primitive type and a “special” scenario, my expectation was autoboxing will also apply here and will work properly, but no – it did not.
Correct way is either to use equals or just use intvalue


About ChandanPandey

Try to come up with a good design as by product of good coding practices

Posted on January 4, 2013, in Java and tagged , . Bookmark the permalink. 2 Comments.

  1. Autoboxing calls Integer.valueOf(int i) which uses a cache for Integer Object going from -127 to 127, for other values a new Integer is created each time. So equality will hold for some values only (may be confusing if you test only with some values, so as you said use .equals is the sure way to go).

    Here is the code for Integer.valueOf(int i)

    public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache
    return IntegerCache.cache[i + offset];
    return new Integer(i);

  2. Let’s think about 1,4 java. If I remember correctly int == Integer was invalid syntax back in 1.4. While Integer == Integer was only reference checking. And sun wnated to have backwards compability. I Integer == Integer suddently would start to mean equals, that would break abckwards compability, so no autboxin when only Objet involved.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: