I got a very strange problem when I'm trying to compare 2 Long variables, they always show false and I can be sure they have the same number value by debugging in Eclipse:
if (user.getId() == admin.getId()) {
return true; // Always enter here
} else {
return false;
}
Both of above 2 return values are object-type Long, which confused me. And to verify that I wrote a main method like this:
Long id1 = 123L;
Long id2 = 123L;
System.out.println(id1 == id2);
It prints true.
So can somebody give me ideas?. I've been working in Java Development for 3 years but cannot explain this case.
== compares references, .equals() compares values. These two Longs are objects, therefore object references are compared when using == operator.
However, note that in Long id1 = 123L; literal value 123L will be auto-boxed into a Long object using Long.valueOf(String), and internally, this process will use a LongCache which has a [-128,127] range, and 123 is in this range, which means, that the long object is cached, and these two are actually the same objects.
because == compares reference value, and smaller long values are cached
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
so it works for smaller long values
Also See
Integer wrapper class and == operator - where is behavior specified?
Stuck on an issue for 4 hours because of the use of == ... The comparison was ok on Long < 128 but ko on greater values.
Generally it's not a good idea to use == to compare Objects, use .equals() as much as possible ! Keep ==, >, <, <= etc. for primitives.
Related
This question already has answers here:
How can I properly compare two Integers in Java?
(10 answers)
Closed 3 years ago.
I was coding an algorithm issue, below code can't pass case
public void pop() {
if (s1.pollFirst() == minStack.peekFirst())
minStack.pollFirst();
}
however below can,
public void pop() {
int tmp = s1.pollFirst() ;
if (tmp == minStack.peekFirst())
minStack.pollFirst();
}
the only difference is how I use s1,pollFirst() return result. I can't figure out real difference here.
Thanks
Comparing two Integer Objects with values less than -128 or bigger than 127 using == will always result in false. However, if you compare Integer with primitive int, it will give you true if the actual value is the same.
int n1=128;
Integer n2=127;
Integer n3=127;
Integer n4=128;
Integer n5=128;
System.out.println(n1==n2); //false
System.out.println(n2==n3); //true
System.out.println(n4==n5); //false
System.out.println(n1==n5); //true
In the second example you are assigning the value to the primitive int, therefore it is automatically unboxed.
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 6 years ago.
I think that the output should be (true true). Sorry for my english
public class A{
public static void main(String[] args) {
Integer i1 = 128;
Integer i2 = 128;
System.out.println(i1 == i2);
Integer i3 = 127;
Integer i4 = 127;
System.out.println(i3 == i4);
}
}
There is a cache of Integer instances for a range of values (at least -128–127), that is used when implicitly converting an int to an Integer.
In this case, 128 is not in the cache, and so each Integer object representing that value is new and distinct.
The value 127, on the other hand, is guaranteed to be in the cache, and so the same instance of Integer is obtained repeatedly.
Integer, as opposed to the primitive int, is an object. Your comparison is comparing two objects of type Integer. I'm kind of surprised you get "false true". If you instead try:
System.out.println(i1.intValue() == i2.intValue());
System.out.println(i3.intValue() == i4.intValue());
you should get the expected result.
I have no idea why these lines of code return different values:
System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));
System.out.println(Integer.parseInt("128")==Integer.valueOf("128"));
The output is:
true
false
true
Why does the first one return true and the second one return false? Is there something different that I don't know between 127 and 128? (Of course I know that 127 < 128.)
Also, why does the third one return true?
I have read the answer of this question, but I still didn't get how it can return true, and why the code in second line returns false.
There's a striking difference here.
valueOf is returning an Integer object, which may have its values cached between -128 and 127. This is why the first value returns true - it's cached - and the second value returns false - 128 isn't a cached value, so you're getting two separate Integer instances.
It is important to note that you are comparing references with Integer#valueOf, and if you are comparing a value that is larger than what the cache supports, it will not evaluate to true, even if the parsed values are equivalent (case in point: Integer.valueOf(128) == Integer.valueOf(128)). You must use equals() instead.
parseInt is returning a primitive int. This is why the third value returns true - 128 == 128 is evaluated, and is of course, true.
Now, a fair bit happens to make that third result true:
An unboxing conversion occurs with respect to the equivalence operator you're using and the datatypes you have - namely, int and Integer. You're getting an Integer from valueOf on the right hand side, of course.
After the conversion, you're comparing two primitive int values. Comparison happens just as you would expect it to with respect to primitives, so you wind up comparing 128 and 128.
The Integer class has a static cache, that stores 256 special Integer objects - one for every value between -128 and 127. With that in mind, consider the difference between these three.
new Integer(123);
This (obviously) makes a brand new Integer object.
Integer.parseInt("123");
This returns an int primitive value after parsing the String.
Integer.valueOf("123");
This is more complex than the others. It starts off by parsing the String. Then, if the value is between -128 and 127, it returns the corresponding object from the static cache. If the value is outside of this range, then it invokes new Integer() and passes in the value, so that you get a new object.
Now, consider the three expressions in the question.
Integer.valueOf("127")==Integer.valueOf("127");
This returns true, because the Integer whose value is 127 is retrieved twice from the static cache, and compared to itself. There's only one Integer object involved, so this returns true.
Integer.valueOf("128")==Integer.valueOf("128");
This returns false, because 128 is not in the static cache. So a new Integer is created for each side of the equality. Since there are two different Integer objects, and == for objects only returns true if both sides are the exact same object, this is going to be false.
Integer.parseInt("128")==Integer.valueOf("128");
This is comparing the primitive int value 128 on the left, with a newly created Integer object on the right. But because it doesn't make sense to compare an int to an Integer, Java will auto-unbox the Integer before doing the comparison; so you end up comparing an int to an int. Since the primitive 128 is equal to itself, this returns true.
Take care of returning values from these methods. The valueOf method returns an Integer instance:
public static Integer valueOf(int i)
The parseInt method returns integer value (primitive type):
public static int parseInt(String s) throws NumberFormatException
Explanation for comparison:
In order to save memory, two instances of the
wrapper objects , will always be == when their
primitive values are the same:
Boolean
Byte
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127
When == is used to compare a primitive to a wrapper, the wrapper will be
unwrapped and the comparison will be primitive to primitive.
In your situation (according to the above rules):
Integer.valueOf("127")==Integer.valueOf("127")
This expression compares references to the same object because it contains Integer value between -128 and 127 so it returns true.
Integer.valueOf("128")==Integer.valueOf("128")
This expression compares references to different objects because they contain Integer values not in <-128, 127> so it returns false.
Integer.parseInt("128")==Integer.valueOf("128")
This expression compares primitive value (left hand side) and reference to the object (right hand side)
so right hand side will be unwrapped and his primitive type will be compared to the left so it returns true.
Integer objects caches between -128 and 127 of 256 Integer
You should not compare object references with == or !=. You should use .equals(..) instead, or better - use the primitive int rather than Integer.
parseInt: Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
valueOf
Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseInt(java.lang.String, int) method. The result is an Integer object that represents the integer value specified by the string.
equivalent to
new Integer(Integer.parseInt(s, radix))
radix - the radix to be used in interpreting s
so if you equal Integer.valueOf() for the integer inbetween
-128 to 127 it returns true in your condition
for lesser than -128 and greater than 127 it gives false
To complement the given answers, also take note of the following:
public class Test {
public static void main(String... args) {
Integer a = new Integer(129);
Integer b = new Integer(129);
System.out.println(a == b);
}
}
This code will also print: false
As user Jay has claimed in a comment for the accepted answer, care must be taken when using operator == on objects, here you're checking if both references are the same, which is not, because they are different objets, although they represent the very same value. To compare objects, you should use the equals method instead:
Integer a = new Integer(128);
Integer b = new Integer(128);
System.out.println(a.equals(b));
This will print: true
You may ask, But then why the first line printed true?. Checking the source code for the Integer.valueOf method, you can see the following:
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
If the param is an integer between IntegerCache.low (defaulted to -128) and IntegerCache.high (calculated at runtime with minimum value 127) then a pre-allocated (cached) object is returned. So when you use 127 as parameter, you're getting two references to same cached object and getting true in the comparison of the references.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Integer == int allowed in java
What is the difference between the following two statements
Long l1 = 2L;
if(l1 == 2)
System.out.println("EQUAL");
if(l1.longValue() == 2)
System.out.println("EQUAL");
They both are giving same result "EQUAL".But my doubt is Long is object. How is it equal?
As already pointed out in the comments, when doing
if(l1 == 2)
Long l1 gets automatically unboxed to its primitive type, long. So the comparison is between long and int.
In the second case, l1.longValue() will return the long value, as a primitive, of the Long represented by the Long object, so the comparison will be again between long and int. Answering your comment, take a look at What is the main difference between primitive type and wrapper class?
The link given in the comments about autoboxing covers this subject quite well.
This behaviour is explained by widening and boxing.
In the first example,
if(l1 == 2)
what happens is as follows:
1: The compiler notices that you are comparing a wrapper (Long) with a primitive value (int), so it boxes the primitive, resulting in:
if (l1 == new Integer(2))
since 2 is an int (it lacks the 'L' at the end).
2: The compiler now notices that we are comparing a Long with an Integer, so it widens the Integer to a Long, resulting in:
if (l1 == new Long(new Integer(2))
3: Now we are comparing two Longs.
The other case is simpler, here the result is simply:
if (2L == 2)
comparing the primitive values, which is allowed even though they are different types.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java question about autoboxing and object equality / identity
Integer i1 = 10;
Integer i2 = 10;
Integer i3 = 210;
Integer i4 = 210;
if(i1 ==i2){
System.out.println("True");
}else{
System.out.println("False");
}
if(i3==i4){
System.out.println("True");
}else{
System.out.println("False");
}
if(Integer.valueOf(10) ==Integer.valueOf(10)){
System.out.println("True");
}else{
System.out.println("False");
}
if(Integer.valueOf(210) ==Integer.valueOf(210)){
System.out.println("True");
}else{
System.out.println("False");
}
The answer is
True
False
True
False
Why it is giving false for 2 and 4 condition ?
Use .equals() to compares Integer.== compares refrences equality
== compares instances not values. Use int instead of Integer and it will work
Note that Integer is an object, not a primitive. You're comparing different object instances.
For this particular example, it's worth reading about boxing.
In Java use the Object function Object.equals(Object) to compare objects. That comparison would only work correctly using the primitive int.