Integer comparison with == [duplicate] - java

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

Related

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

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 ==.

This 'if' evaluation in Java with three simultaneous expressions [duplicate]

This question already has answers here:
How to make loop infinite with "x <= y && x >= y && x != y"?
(4 answers)
Closed 7 years ago.
I had this question in my Java test where I had to assign values to a and b so this expression evaluates to true:
(a<=b && b<=a && a!=b)
Sadly, I had no idea what the answer was.
There's a simple trick here.
You cannot think this through with boolean logic only. Using that, this combination...
a is less than or equal to b, and
b is less than or equal to a, and
a is not equal to b
...would never return true.
However, the != operator compares references if its operands are objects.
So, the following will return true:
Integer a = 1;
Integer b = new Integer(1);
System.out.println(a<=b && b<=a && a!=b);
What happens here is: a as an object reference is not equal to b as an object reference, although of course they hold equal integer values.

How can "a <= b && b <= a && a != b" be true? [duplicate]

This question already has answers here:
How to make loop infinite with "x <= y && x >= y && x != y"?
(4 answers)
How can i define variables to make an infinity while loop with these conditions? [closed]
(4 answers)
Closed 9 years ago.
Here is the code i have to figure it out how is it possible. I have a clue but i do not know how to do it. I think it is about negative and positive numbers and maybe the variable modifiers as well. I am a beginner i looked the solution everywhere but i could not find anything usable.
the question is that: You need to declare and initialize the two variables. The if condition must be true.
the code:
if( a <= b && b <= a && a!=b){
System.out.println("anything...");
}
I appreciate you taking the time.
This is not possible with primitive types. You can achieve it with boxed Integers:
Integer a = new Integer(1);
Integer b = new Integer(1);
The <= and >= comparisons will use the unboxed value 1, while the != will compare the references and will succeed since they are different objects.
This works too:
Integer a = 128, b = 128;
This doesn't:
Integer a = 127, b = 127;
Auto-boxing an int is syntactic sugar for a call to Integer.valueOf(int). This function uses a cache for values less than 128. Thus, the assignment of 128 doesn't have a cache hit; it creates a new Integer instance with each auto-boxing operation, and a != b (reference comparison) is true.
The assignment of 127 has a cache hit, and the resulting Integer objects are really the same instance from the cache. So, the reference comparison a != b is false.
Another rare case for class-variables may be that another thread could change the values of a and b while the comparison is executing.

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

Autoboxing Question [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Wrapper class and == operator
Saw this code in a website when i was learning about autoboxing..
Integer i1 = 1;
Integer i2 = 1;
// true
System.out.println(i1 == i2);
Integer i3 = -200;
Integer i4 = -200;
// false
System.out.println(i3 == i4);
I can understand why the 2nd comparison gives false (its comparing references). But why is it giving true for the first one ?
Because the first several Integer objects (from -128 to 127, inclusive, to be precise) are cached and reused by the JVM, so i1 and i2 are references to the same physical object.
This is also true to Long, Short and Byte btw. See this article for a more detailed explanation.
Boxing is guaranteed to use the same cached objects for a range of values.
Beyond that the JVM can use a larger cache, but it's not guaranteed. From the JLS section 5.1.7:
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Categories

Resources