I want to compare two Long objects values using if
conditions. When these values are less than 128, the if
condition works properly, but when they are greater than or equal to 128, comparison fails.
Example:
Long num1 = 127;
Long num2 = 127;
if (num1 == num2) {
// Works ok
}
Comparison on the code above works properly, but fails in the code below:
Long num1 = 128;
Long num2 = 128;
if (num1 == num2) {
// Does NOT work
}
Why is there a problem in comparing Long variables with values greater than 127? If the variables data types are changed to long primitives, then the comparisons work for all cases.
This question is related to
java
comparison
autoboxing
Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.
This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).
For example:
If we set java.lang.Integer.IntegerCache.high=500;
then values from -128 to 500 will get cached and
Integer a=498;
Integer b=499;
System.out.println(a==b)
Output will be "true".
Float and Double objects never gets cached.
Character will get cache from 0 to 127
You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.
1) type cast both objects into primitive values and compare
(long)val3 == (long)val4
2) read value of object and compare
val3.longValue() == val4.longValue()
3) Use equals() method on object comparison.
val3.equals(val4);
Comparing non-primitives (aka Objects) in Java with ==
compares their reference instead of their values. Long
is a class and thus Long
values are Objects.
The problem is that the Java Developers wanted people to use Long
like they used long
to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long
-values will be changed to Long
-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.
So to be safe and to have predictable results always use .equals()
to compare objects and do not rely on autoboxing in this case:
Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }
num1
and num2
are Long objects. You should be using equals()
to compare them. ==
comparison might work sometimes because of the way JVM boxes primitives, but don't depend on it.
if (num1.equals(num1))
{
//code
}
Source: Stackoverflow.com