-1

Today i come across the peculiar behaviour of equlaity operator.

I’d expect the answer to be false. We’re testing for reference equality here, after all – and when you box two values, they’ll end up in different boxes, even if the values are the same, right

Object x = 129;
Object y = 129;
boolean equality = (x == y);
System.out.println(equality);

OUTPUT : FALSE

Object x = 12;
Object y = 12;
boolean equality = (x == y);
System.out.println(equality);

OUTPUT : TRUE

Can some one help me understanding why this is behaving like this.

Tsung-Ting Kuo
  • 1,153
  • 6
  • 16
  • 20
Sachin Sachdeva
  • 10,526
  • 37
  • 100
  • This is a [two's complement trick](http://stackoverflow.com/questions/3621067/why-is-the-range-of-bytes-128-to-127-in-java) don't get fooled ... ;-) – Edward J Beckett Nov 17 '15 at 06:54

3 Answers3

1

== is a reference comparison. It looks for the "same" object instead of "similar" object. Since values between -128 to 127 are returned from cache and the same reference is returned, your second comparison returns true. But values above 127 are not returned from cache so the reference differs and your first comparison returns false.

Good question btw :)

leo
  • 61
  • 2
0

It is always recommended to use object1.equals(onject2) to check for equality because when you compare using == it is reference comparison and not comparison of value.

shree.pat18
  • 19,860
  • 3
  • 35
  • 56
0

Integer is a wrapper class for int.

Integer != Integer compares the actual object reference it actual compares objects ,

where int != int will compare the values.

As already stated, values -128 to 127 are cached, so the same objects are returned for those.so thats why output is true.

But If outside that range ie (129), separate objects will be created so the reference will be different.so thats why output is false

for correct output: 1. Make the types int or

2.Cast the types to int or

3.Use .equals()

vijay
  • 35
  • 6