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

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!


Solution 1:

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

Solution 2:

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.

Solution 3:

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.

Solution 4:

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