Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why == resulting in true , in Long object [duplicate]

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.

like image 732
anshulkatta Avatar asked Dec 20 '22 04:12

anshulkatta


1 Answers

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
}
like image 64
NPE Avatar answered Jan 01 '23 22:01

NPE