Java Wrapper equality test
Asked Answered
A

5

23
  public class WrapperTest {

    public static void main(String[] args) {

        Integer i = 100;
        Integer j = 100;

        if(i == j)
            System.out.println("same");
        else
            System.out.println("not same");
    }

   }

The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.

Ascent answered 19/1, 2009 at 5:5 Comment(1)
Very interesting question, and I did not know Java behaved this way. I tend to use equals() whenever I can, so I have been lucky enough to avoid this problem.Mckenna
V
21

In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):

private static class IntegerCache {
    private IntegerCache(){}

    static final Integer cache[] = new Integer[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Integer(i - 128);
    }
}

See also: http://www.owasp.org/index.php/Java_gotchas

Valdes answered 19/1, 2009 at 5:14 Comment(0)
G
7

Basically Integers between -127 and 127 are 'cached' in such a way that when you use those numbers you always refer to the same number in memory, which is why your == works.

Any Integer outside of that range are not cached, thus the references are not the same.

Glorify answered 19/1, 2009 at 5:12 Comment(0)
A
5

@tunaranch is correct. It is also the same issue as in this Python question. The gist is that Java keeps an object around for the integers from -128 to 127 (Python does -5 to 256) and returns the same object every time you ask for one. If you ask for an Integer outside of this fixed range, it'll give you a new object every time.

(Recall that == returns whether two objects are actually the same, while equals compares their contents.)

Edit: Here's the relevant paragraph from Section 5.1.7 of the Java Language Specification:

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Note that this also describes what happens with other types.

Anthracene answered 19/1, 2009 at 5:11 Comment(0)
T
4

It's to do with equality and autoboxing: http://web.archive.org/web/20090220142800/http://davidflanagan.com/2004/02/equality-and-autoboxing.html

Tildie answered 19/1, 2009 at 5:8 Comment(0)
A
0

Your code doesn't compile. This is what I get:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Type mismatch: cannot convert from int to Integer Type mismatch: cannot convert from int to Integer

at WrapperTest.main(WrapperTest.java:5)

Variables i and j are instances of Integer object. Don't compare instances of object using "==" operator, use "equals" method instead.

Greetings

Agathaagathe answered 19/1, 2009 at 8:53 Comment(1)
I guess you are using java 1.4..try it with Java 1.5Ascent

© 2022 - 2024 — McMap. All rights reserved.