What is the reason for this strange Java behavior?
•
Java
I want to test the '= =' operator on long. This is what I found: the following code:
public static void main(final String[] args) { final Long n = 0L; final Long m = 0L; System.out.println(n + " == " + m + " : " + (n == m)); final Long a = 127L; final Long b = 127L; System.out.println(a + " == " + b + " : " + (a == b)); final Long A = 128L; final Long B = 128L; System.out.println(A + " == " + B + " : " + (A == B)); final Long x = -128L; final Long y = -128L; System.out.println(x + " == " + y + " : " + (x == y)); final Long X = -129L; final Long Y = -129L; System.out.println(X + " == " + Y + " : " + (X == Y)); }
Output:
0 == 0 : true 127 == 127 : true 128 == 128 : false -128 == -128 : true -129 == -129 : false
The only explanation I can think of is that the JVM stores all long values in [- 128127] in the Perl space and provides their addresses to long and all values outside the above range. It creates a new allocation for each static value, which is encountered in the code
Am I right? Under what circumstances must we pay attention to similar behavior?
PS. I know I should use nullcheck and then use Equals () to compare objects, but I'm curious if anyone knows the answer
edit
After jtahlborn answered who gave me keyword automatic boxing, I found this wonderful article about well documented answer
Solution
This is the result of automatic packing See long valueOf().
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码