4

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.

Community
  • 1
  • 1
anshulkatta
  • 2,044
  • 22
  • 30

3 Answers3

7

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
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
4

I beleive it is due to the auto-unboxing when you do (story * 2) resulting in primitive value 2000L. And when you compare it against tail which also hold 2000L value, hence the result is true. Check here the x==y rule when one item is primitive.

enter image description here

Source: http://www.javapractices.com/topic/TopicAction.do?Id=197

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

Multiplication, addition and other operations can be carried out on primitives only...

When you carry out those operations all the boxed primitives will be unboxed and treated as primitive types.

So in your example == is checking long equality not object equality.

Thihara
  • 7,031
  • 2
  • 29
  • 56