Reputation: 5959
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?
Upvotes: 1
Views: 155
Reputation: 10249
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
Upvotes: 1
Reputation: 11
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
Upvotes: 1
Reputation: 7624
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.
Upvotes: 1
Reputation: 73528
The int value goes to Integer.MIN_VALUE, underflows and goes to Integer.MAX_VALUE which is what you're seeing.
Upvotes: 0
Reputation: 159754
x
is decremented and then underflows reaching Integer.MAX_VALUE
Upvotes: 10