Why == the result is true in the Long object

In this code snippet (story * 2) == tail , True

and false for distance + 1 != tail .

== checks for links, since Long is immutable, it will be false for two different objects,

Here, the value of story * 2 becomes equal with respect to tail , but these are two different objects, not a compile-time constant for the union.

  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 there was no explanation for this.

+4
source share
3 answers

I believe this is due to automatic unpacking when you do (story * 2), resulting in a primitive value of 2000L. And when you compare it with the tail, which also has a value of 2000L, then the result is correct. Check here the rule x == y when one element is primitive.

enter image description here

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

+4
source

When you perform arithmetic operations with wrapped primitives (for example, Long ), they are automatically unpacked into the original primitives (for example, Long ).

Consider the following:

 (story * 2) == tail 

First, the story auto-unboxed in Long and multiplied by two. To compare the Long result with Long on the right, the latter is also automatically unpacked.

There is no link comparison 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 } 
+7
source

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

When you perform these operations, all boxed primitives will be unpacked and processed as primitive types.

So, in your == example, equality of duration of equality is checked, not equality.

0
source

Source: https://habr.com/ru/post/1487803/


All Articles