What's the cause of this strange Java behavior?

Viewed 250

I wanted to test the '==' operator on Longs and this is what I've 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));
}

outputs:

0 == 0 : true
127 == 127 : true
128 == 128 : false
-128 == -128 : true
-129 == -129 : false

The only explanation I could come up with was that the JVM stores all long values inside [-128, 127] in the Perm space, and gives their address to Longs and to everything outside the above range it creates a new allocation for each static value met in the code.

Am I close to being right? In what situations do we have to be aware of similar behaviors?

PS. I know I should use a nullcheck and then .equals() to compare objects, but I was curious if anyone knew the answer.

EDIT

After jtahlborn's answer who gave me the keyword auto-boxing I've found this great article with the well-documented answer

3 Answers
Related