In this piece of code (story * 2) == tail
is getting True
and false
for distance + 1 != tail
.
==
checks for reference , as Long is immutable , it will false for two different objects,
Here The value story * 2
is getting equal in reference to tail
, but they are two different objects and not a compile time constant for pooling.
public class Test2
{
public static void main(String [] args) {
Long tail = 2000L;
Long distance = 1999L;
Long story = 1000L;
System.out.println(tail > distance);
System.out.println((story * 2) == tail);
if((tail > distance) ^ ((story * 2) == tail))
System.out.print("1");
System.out.println(distance + 1 != tail);
System.out.println((story * 2) == distance);
if((distance + 1 != tail) ^ ((story * 2) == distance))
System.out.print("2");
}
I checked here , but no explanations for this.
When you perform arithmetic operations on wrapped primitives (such as Long
), they are automatically unboxed into raw primitives (e.g. long
).
Consider the following:
(story * 2) == tail
First, story
is auto-unboxed into a long
, and is multiplied by two. To compare the resulting long
to the Long
on the right-hand side, the latter is also auto-unboxed.
There is no comparison of references here.
The following code demonstrates this:
public static void main(String[] args) {
Long tail = 2000L;
Long story = 1000L;
System.out.println((story * 2) == tail); // prints true
System.out.println(new Long(story * 2) == tail); // prints false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With