开发者

Expected this loop to be infinite but it is not

Here is my Java code:

public class Prog1 {
    public static void main(String[] args) {
        int x = 5;
        while (x > 1) { 
            x = x + 1;
            if (x < 3)
                System.out.println("small x");   
        }
    }
}

And this is the output:

small x

I was expecting an infinite loop... Any idea why it is behaving this w开发者_运维问答ay?


There is an infinite loop. Just in some time, x get so bit that it overflows the limit of a signed int, and it goes negative.

public class Prog1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int x = 5;
        while (x > 1) { 
            x = x + 1;
            System.out.println(x);
            if(x < 3)
                System.out.println("small x");   
        }
    }
}


x starts out 5. Then as you loop through it goes to 6, 7, 8, etc. Eventually it hits the largest possible int. The next x=x+1 sets it to the most negative int, negative 2 billion-whatever. This is less than 3 so the message is output. Then you execute the while condition again which now fails, exiting the loop.

So while it appears to be an infinite loop, it isn't really.

Is this a homework problem? Why would you have written such odd code?


Java integers are signed, and they overflow (as in C and many other languages). Try this to check this behaviour:

public class TestInt {
   public static void main(String[] args) {
     int x = Integer.MAX_VALUE;
     System.out.println(x);
     x++;
     System.out.println(x);
   }
}


X is overflowing the limits of an int. Check the value by adding a println statement for x

public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
while (x > 1) { 
    x = x + 1;
    if(x < 3){
        System.out.println(x);
        System.out.println("small x");   
    }
}

My jvm showed x as -2147483648

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜