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

Java Puzzle #14: Integers

Contents

  • Java Puzzle #14: Integers
    • Answer
    • Explanation

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.


Published

Okt 22, 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