In java equal and == behavior

Please explain the behavior below.

public class EqAndRef { public static void main(String[] args) { Integer i = 10; Integer j = 10; Double a = 10D; Double b = 10D; System.out.println(i.equals(j)); System.out.println(i == j); System.out.println(a.equals(b)); System.out.println(a == b); } } 

Jdk 6 output

 true true true false 

why a == b is false and i == j not false?

+6
source share
2 answers

Initialize Integer as follows, then you will get the difference, as @ 5gon12eder said

The integer si and j are built (by means of automatic boxing) from integer literals from the range from -128 to 127, which are guaranteed to be combined by the JVM, therefore they use the same object (see, Therefore, they compare equal by object links.

try this code to initialize integers

  Integer i = new Integer(10); Integer j = new Integer(10); 
+2
source

Integer i and j built (using automatic boxing) from integer literals ranging from -128 to 127 and, therefore, they will be combined by the JVM, so they use the same object (see flyweight pattern ). Therefore, they are compared using object references.

For Double a and b on the other hand, such a union guarantee does not exist and, in your case, you have two different objects that did not compare the same.

Using == to compare objects, if you do not want to verify your identity, should be considered suspicious and should be avoided. The equals methods of both types are overridden to compare values ​​in the box (as opposed to the identity of the object), so they return true in both cases (and should be used).

+19
source

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


All Articles