Why is == true for some Integer objects? [duplicate]
Asked Answered
C

4

20

Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?

I have copied the following program snippet from the Khalid Mughal SCJP, but I am unable to
understand the output.

 public class RQ200_60 {
    public static void main(String[] args) {
        Integer i = -10;
        Integer j = -10;
        System.out.print(i==j);         // output: true -- why true?
        System.out.print(i.equals(j));  // output: true
        Integer n = 128;
        Integer m = 128;
        System.out.print(n==m);         // output: false
        System.out.print(n.equals(m));  // output: true
    }
}      

The above program giving output true for the first print statement but it supposed to give false because it is reference comparison with == relational operator. But third print gives false and I don't understand this inconsistency.

Explanations are greatly appreciated!

Cumings answered 8/12, 2011 at 7:7 Comment(1)
G
36

In the first case, both the objects i and j are pointing to the same cached object. By default, the range between -128 and 127 are cached as Integer Object. We can increase the range using JVM arguments

Gilbye answered 8/12, 2011 at 7:10 Comment(2)
+1 Interesting, didn't know that was configurable.Myogenic
I also didn't know it's configurable. Autoboxed values from -128 to 127 must be identity-equal according to JLS 5.1.7Merci
O
13

The answers about caching are correct. However, if you go...

Integer i = new Integer(10);
Integer j = new Integer(10);

...then you avoid the caching and the results will be what you expected.

Orthoepy answered 8/12, 2011 at 7:17 Comment(1)
@pst thanks for the edit. Typing on my Nook is a bit awkward.Orthoepy
P
8

Integer objects may be cached for the ones that represent a value close to 0. (The specification for the implementation may tell you some details). This is presumably to save memory (values close to 0 are common, and it would waste a lot of memory to make a new object for every variable with the same value).

== checks whether two things are the same object; you may or may not have the same Integer object for any two given variables with the same value. You are not supposed to check with == because you are not supposed to care whether it is the same object; it is the value of an Integer that matters, not its identity.

Psychiatry answered 8/12, 2011 at 7:10 Comment(0)
T
1

Here in this case the Integer i and Integer j holding the integer values which are in range of integer, range of an Integer is -128 to 128, and Integer n and Integer m exceeds the range of Integer

Therewithal answered 8/12, 2011 at 8:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.