Why does comparing Integer values using == and equals() give different results? [duplicate] - java

This question already has answers here:
Java: Integer equals vs. ==
(7 answers)
How can I properly compare two Integers in Java?
(10 answers)
Closed 4 years ago.
Consider:
Integer i = 11;
Integer j = 11;
Integer h = 10000;
Integer k = 10000;
System.out.println((i==j));
System.out.println((i.equals(j)));
System.out.println((h==k));
System.out.println((h.equals(k)));
The output is:
true
true
false
true
Actually for h==k, it should also give true. What is the explanation?

Because == checks object references while equals checks actual values. They are not guaranteed to yield the same result.
In some cases they do give the same result, but that's because your JVM is interning some of the Integer objects. Meaning, it maintains a cache of integer objects. So for example if you ask for an Integer value of 10, it might return the same object instance. But there are no guarantees as to which values would be interned. So it is always advisable to use equals instead of relying on ==.

Related

Why two objects of the Integer class with same value gives false on equality check when value is greater than 127? [duplicate]

This question already has answers here:
Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?
(8 answers)
Closed 1 year ago.
class MyClass {
public static void main(String[] args) {
Integer a = 5;
Integer b = 5;
Integer c = 129;
Integer d = 129;
System.out.println(a == b);
System.out.println(c == d);
}
}
The output is
true
false
Why is this happening?
When using Integer wrapper objects instead of the int primitive, java globally caches these objects in this range because they are used often. This can speed up execution. Because these objects are cached, they are equal, while above the threshold a new objects is created of every integer.
When you want to compare Integers instead of ints use the .equals() method instead of ==.

In java equal and == behaviour [duplicate]

This question already has answers here:
Java: Integer equals vs. ==
(7 answers)
Closed 8 years ago.
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?
The Integers 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 Doubles 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 Integers 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);

Integer comparison with == [duplicate]

This question already has answers here:
Integer wrapper objects share the same instances only within the value 127? [duplicate]
(5 answers)
Closed 8 years ago.
I was writing some test code and found one strange thing, and still confused how this is happening?
Integer i1 = 220;
Integer i2 = 220;
System.out.println(i1 == i2);
prints false as expected. But
Integer i1 = 20;
Integer i2 = 20;
System.out.println(i1 == i2);
prints true, but both are different references referring to different objects (I assume that).
How come second snippet prints true?
The == operator only works for Integer values between -128 and 127. That is why it doesn't work for 220 but does for 20. In general it is best to always use .equals() when comparing Integers and you should never rely on the == operator.
More information can be found here: https://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

Memory allocation/reference comparison for ints and Integers [duplicate]

This question already has answers here:
Inconsistent behavior on java's ==
(7 answers)
How != and == operators work on Integers in Java? [duplicate]
(5 answers)
Closed 9 years ago.
With the following:
String a = new String("test");
String b = "test";
System.out.println(a == b); //false
We get false, since String a is an object, so a points to a different location in memory than the string literal, b. I wanted to see how this worked for int and Integer:
Integer x = new Integer(5);
int y =5;
System.out.println(x == y); //true
I though that x.equals(y) would be true, but x == y would be false as it is in the case with Strings. I understand that we compare ints with ==, but I figured that comparing an int to an Integer would be different. Why is this not the case?
I assume that in this case using == won't work for comparing references, so how would we do it (not sure if this is practical, but I'd like to know)?
Because of boxing and unboxing in java
Converting an int to an Integer, a double to a Double, and so on. If
the conversion goes the other way, this is called unboxing.
Autoboxing/unboxing is a pure convenience feature that allows you to assign values of a primitive type a reference of a wrapper class and vice versa, with the compiler automatically adding the code to convert between the two.
Boxing and unBoxing and SEE HERE ALSO

Why is == true for some Integer objects? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
I have copied the following program snippet from the Khalid Mughal SCJP, but I am unable to
understand the output.
public class RQ200_60 {
public static void main(String[] args) {
Integer i = -10;
Integer j = -10;
System.out.print(i==j); // output: true -- why true?
System.out.print(i.equals(j)); // output: true
Integer n = 128;
Integer m = 128;
System.out.print(n==m); // output: false
System.out.print(n.equals(m)); // output: true
}
}
The above program giving output true for the first print statement but it supposed to give false because it is reference comparison with == relational operator. But third print gives false and I don't understand this inconsistency.
Explanations are greatly appreciated!
In the first case, both the objects i and j are pointing to the same cached object. By default, the range between -128 and 127 are cached as Integer Object. We can increase the range using JVM arguments
The answers about caching are correct. However, if you go...
Integer i = new Integer(10);
Integer j = new Integer(10);
...then you avoid the caching and the results will be what you expected.
Integer objects may be cached for the ones that represent a value close to 0. (The specification for the implementation may tell you some details). This is presumably to save memory (values close to 0 are common, and it would waste a lot of memory to make a new object for every variable with the same value).
== checks whether two things are the same object; you may or may not have the same Integer object for any two given variables with the same value. You are not supposed to check with == because you are not supposed to care whether it is the same object; it is the value of an Integer that matters, not its identity.
Here in this case the Integer i and Integer j holding the integer values which are in range of integer, range of an Integer is -128 to 128, and Integer n and Integer m exceeds the range of Integer

Categories

Resources