Java Puzzle #14: Integers

· by

What is the output of the following script?

public class SomeClass {
    public static void main(String[] args) {
        int x = 2147483647; // 2147483647 == 2**31 - 1
        if (x < 2*x) {
            System.out.println("Everything's ok:");
        } else {
            System.out.println("It's weird:");
        }

        System.out.println("x   = " + x);
        System.out.println("2*x = " + 2*x);
    }
}

. . . . . . . . . . . . . . . . . . . . . .

Answer

It's weird:
x   = 2147483647
2*x = -2

Explanation

2*x is out of Java Integer range, so it comes back at the other end.