Reputation: 39374
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.
Upvotes: 23
Views: 5776
Reputation: 1586
It's to do with equality and autoboxing: http://web.archive.org/web/20090220142800/http://davidflanagan.com/2004/02/equality-and-autoboxing.html
Upvotes: 4
Reputation: 5180
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
Upvotes: 0
Reputation: 9928
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
Upvotes: 21
Reputation: 31981
@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
, abyte
, achar
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.
Upvotes: 5
Reputation: 59378
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.
Upvotes: 7