Java traps · Java

Java: 128 == 128 is FALSE?!PRO

Watch the video

Java caches Integers from -128 to 127, so == works… until it doesn't. Plus the same trap with Long.

// 127 == 127 but 128 != 128 ?!  — Java caches Integer objects from -128 to 127.
// == compares the BOXES; outside the cache you get two different boxes.
public class Main {
    public static void main(String[] args) {
        Integer a = 127, b = 127;
        System.out.println(a == b);          // true
        Integer c = 128, d = 128;
        System.out.println(c == d);          // false ?!
        System.out.println(c.equals(d));     // true ✓
        System.out.println(c.intValue() == d.intValue()); // true ✓

        // Bonus trap: Long has the same cache
        Long x = 1000L, y = 1000L;
        System.out.println(x == y);          // false ?!
    }
+ 2 more lines in the app (Pro)
Open code J3 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code J3 in Code Library.