Java traps · Java

Java: Math.abs() returned a NEGATIVE?!PRO

Watch the video

Integer.MIN_VALUE has no positive twin in an int. Two fixes, plus the MAX_VALUE + 1 wrap-around.

// Math.abs() returned a NEGATIVE ?!  — Integer.MIN_VALUE has no positive twin in an int.
public class Main {
    public static void main(String[] args) {
        int x = Integer.MIN_VALUE;            // -2147483648
        System.out.println(Math.abs(x));      // -2147483648 ?!
        System.out.println(Math.abs((long) x)); // 2147483648 ✓

        // Or check first and refuse the one value that can't flip
        if (x == Integer.MIN_VALUE) {
            System.out.println("can't make it positive in an int ✓");
        }

        // Bonus trap: the same wrap-around on +1
        int max = Integer.MAX_VALUE;
        System.out.println(max + 1);          // -2147483648 ?!
+ 3 more lines in the app (Pro)
Open code J4 in Pocket Compiler Download the Pocket Compiler app — free

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