0

output are: true,true*,false* what is going on case=1 and case=2 if case:1 is true than why? value 5 has different memory allocation? we know that '==' operator compare based on memory or refrence

   Integer a=new Integer(5);
   Integer b=a;
   System.out.println(a==b);  //true i know 
  /*case:1 */System.out.println(a==5); //true? why

  /*case :2 */ System.out.println(a==new Integer(5)); // false ? why 
  • Interesting note is that the Integer class keeps a cache of the Integer between -128 and 127. So, when you do stuff like Integer a = 5; or Integer.valueOf(5), you actually end up with the very same Integer, from that cache. In your case, you used the constructor and that cache is not used. So, different references. – Thomas May 05 '16 at 06:15

2 Answers2

1

Check java doc for Integer https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

Correct way of comparing objects is using equals

public boolean equals(Object obj)

Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object. Overrides: equals in class Object Parameters: obj - the object to compare with. Returns: true if the objects are the same; false otherwise.

Iwo Kucharski
  • 3,735
  • 3
  • 50
  • 66
Murthy
  • 19
  • 3
0

For case 2, the Integer a is auto-unboxed yielding the primitive 5, which is equal to 5.

For case 3, a new Integer object is created, which has a different address to that equality cannot be checked via ==. You'd have to use the equals-method in this case: (a.equals(new Integer(5)) is true)

mtj
  • 3,381
  • 19
  • 30