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!
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.
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 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With