-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
0

2 Answers 2

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. 
Sign up to request clarification or add additional context in comments.

2 Comments

is it so.did not know about a local cache. seems an awesome answer
@vikeng21 - Yep. That's the case. check oracle doc
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.