Please can you explain the below behaviour.
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);
}
}
Output on jdk 6
true
true
true
false
why a==b is false and i==j not false?
Differences between == and equals() method in Java == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.
equals() method. The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
The equality operator or "==" compares two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).
The Integer
s i
and j
are constructed (via auto boxing) from integer literals from the range –128 to 127 and thus are guaranteed to be pooled by the JVM so the same object (see flyweight pattern) is used for them. Hence, they compare identical by object references.
For the Double
s a
and b
on the other hand, no such pooling guarantee exists and, in your case, you got two different objects that did not compare identical.
Using ==
to compare objects if you don't mean to check identity is to be considered suspect and should be avoided. The equals
methods of both types are overridden to compare the boxed values (as opposed to object identity) which is why they return true
in both cases (and should be used).
Initialize the Integer
s the following way then you will get the difference as @5gon12eder said
The Integer s i and j are constructed (via auto boxing) from integer literals from the range –128 to 127 which are guaranteed to be pooled by the JVM so the same object (see flyweight pattern ) is used for them. Hence, they compare equal by object references.
try this code to initialize your integers
Integer i = new Integer(10);
Integer j = new Integer(10);
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