简体   繁体   中英

what's wrong with this program

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

x递减,然后下溢达到Integer.MAX_VALUE

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.

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

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

int值转到Integer.MIN_VALUE,下溢并转到您正在查看的Integer.MAX_VALUE。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM