Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are 2 Long variables not equal with == operator in Java?

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.

like image 260
Brady Zhu Avatar asked Oct 21 '13 03:10

Brady Zhu


People also ask

Does == work for long in Java?

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

Can we compare long with ==?

Long is a wrapper class for the primitive type long. Since they are objects and not primitive values, we need to compare the content of Long instances using . equals() instead of the reference comparison operator (==). In some cases, we may get the idea that == is okay, but looks are deceiving.

What does the == operator do in Java?

== operator is a type of Relational Operator in Java used to check for relations of equality. It returns a boolean result after the comparison and is extensively used in looping statements and conditional if-else statements.


1 Answers

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

like image 150
BlackJoker Avatar answered Sep 21 '22 03:09

BlackJoker