Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

integer

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!

like image 310
yagnya Avatar asked Dec 08 '11 07:12

yagnya


2 Answers

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.

like image 37
user949300 Avatar answered Oct 17 '22 09:10

user949300


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

like image 104
Prince John Wesley Avatar answered Oct 17 '22 08:10

Prince John Wesley