1

I've a code snippet:

class WhileTest
{
    public static void main(String s[])
    {
        int x=12;
        while(x<13)
        {
            x--;
        }
        System.out.println(x);
    }
}

The output of the above program is: 2147483647

Why so?

Code on ideone

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117

5 Answers5

10

x is decremented and then underflows reaching Integer.MAX_VALUE

Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Note that x = 12, and you keep subtracting. This results in x always being less than 13. That is until Integer Overflow occurs (when x gets to the lowest possible int (Integer.MIN_VALUE)), and the number wraps around to the maximum possible integer (Integer.MAX_VALUE) which is greater than 13 and the loop ends.

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
1

you decrease x each iteration.

when x = -2147483648 (which is the MIN_VALUE of Integer) the next step of x-- will set x = +2147483647 (which is the MAX_VALUE of Integer) because of the overflow (or underflow, however you call it).

and since 2147483647 < 13 = false you will see the println

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
1

Each iteration reduces the size of x, so theoretically x will never be greater than or equal to 13, right?

Sure, if ints behave just like integers. But they don't. Int's have a maximum and minimum size, because of how they stored in your computer. In Java, an int is a 32-bit signed number; an int's maximum size is 2^31-1; it's minimum size is -2^31.

What happens when x is the minimum size, -2^31, in that loop? -2^31 - 1 < 13, so why does the loop condition fail? That number can't be represented by an int. The way ints behave is that they wrap around.

int x = Integer.MIN_VALUE; // x = -2^31
x--;
x == Integer.MAX_VALUE; //True. x == 2^31-1

2^21 - 1 is larger than 13, and the loop condition fails. The print statement is run when x is Integer.MAX_VALUE. And what is the value of 2^31 - 1? 2147483647

Ed Shaw
  • 11
  • 1
0

The int value goes to Integer.MIN_VALUE, underflows and goes to Integer.MAX_VALUE which is what you're seeing.

Kayaman
  • 72,141
  • 5
  • 83
  • 121