• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Java Puzzle #13: Absolute value weirdness

Contents

  • Java Puzzle #13: Absolute value weirdness
    • Answer
    • Explanation

What does the following snippet output?

public class SomeClass {
    public static void main(String[] args) {
        int a = -10;
        int b = -2147483648; // -2147483648 == -2**31

        if (Math.abs(a) < -1) {
            System.out.println("|a| < -1");
        } else {
            System.out.println("|a| >= -1");
        }

        if (Math.abs(b) < -1) {
            System.out.println("|b| < -1");
        } else {
            System.out.println("|b| >= -1");
        }

        System.out.println("|a| = " + Math.abs(a));
        System.out.println("|b| = " + Math.abs(b));
    }
}

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

Answer

|a| >= -1
|b| < -1
|a| = 10
|b| = -2147483648

Explanation

Integer values range (in Java) from -2147483648 to 2147483647. This means, the absolute value of -2147483648 is not in the integer range. For more details, see this SO answer.


Published

Okt 19, 2012
by Martin Thoma

Category

Code

Tags

  • Java 36
  • Programming 52
  • puzzle 22

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor