I’ve been learning Java for quite a while and recently stumbled upon a strange result, during Long comparison.
Here is a piece of code:
public class Test {
public static void main(String[] args) {
Long a = 100L;
Long b = 100L;
Long c = 150L;
Long d = 150L;
System.out.println(a == b);
System.out.println(c == d);
}
}
true
false
I know that while Java doesn’t support your general comparison between reference types with ==, it usually caches all constant values that you hardcode and then smart compare them.
And I honestly believed that, until my code crashed. After some tedious debugging I found the bug, and even reproduced it in few lines.
What is going on here?
>Solution :
Java caches values from 0-127. So, == on Uppercase Long will be true for those values. But all others, false.
But that is not behaviour you should depend on. Just use Long::equals or Objects::equals.
Here is a code example.
private class SOQ_20221222_1
{
public SOQ_20221222_1()
{
Long a = 100L;
Long b = 100L;
Long c = 101L;
Long d = 101L;
Long e = 102L;
Long f = 102L;
Long g = 126L;
Long h = 126L;
Long i = 127L;
Long j = 127L;
Long k = 128L;
Long l = 128L;
Long m = 129L;
Long n = 129L;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(e == f);
System.out.println(g == h);
System.out.println(i == j);
System.out.println(k == l);
System.out.println(m == n);
}
}
true
true
true
true
true
false
false