-1
public class Problem {

    public static void main(String args[]){
        Integer a=200;
        Integer b=200;
        Integer c=20;
        Integer d=20;

        System.out.println(a==b);
        System.out.println(a.equals(b));
        System.out.println(c==d);
        System.out.println(c.equals(d));
    }
}

output

false
true
true
true
Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
pratik deshai
  • 2,454
  • 2
  • 9
  • 12

2 Answers2

3

Integer class keeps a local cache between -128 to 127 and returns the same object. So,

    Integer a=200; --> Internally converted to Integer.valueOf(200);
    Integer b=200; // not same as a
    Integer c=20;
    Integer d=20; // same as c

    Integer c=new Integer(20);
    Integer d=new Integer(20);
    c==d --> returns false; because you are comparing references. 
TheLostMind
  • 35,468
  • 12
  • 66
  • 99
1

Compare objects only using equals except you really want to make sure both are the same objects not just equal. In case of the boxed primitives I believe that I have Seen once that some basic numbers are cached so that in these cases Java will return one and the same object. I can't verify this right now but this would explain the behavior you are facing.

shillner
  • 1,748
  • 13
  • 23