This cycle was expected 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 result:

small x

I was expecting an endless loop ... Any idea why it behaves this way?

+3
source share
4 answers

x starts 5. Then, when you go through it, it goes to 6, 7, 8, etc. In the end, it falls into the highest possible int value. The next x = x + 1 sets it to the most negative int, the negative 2 billion - independently. This is less than 3, so a message is displayed. Then you fulfill the while condition again, which now fails, exiting the loop.

So, although it is an infinite loop, in fact it is not.

Is this a home problem? Why did you write such odd code?

+4
source

. - x , int, .

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");   
        }
    }
}
+6

X int. , println 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");   
    }
}

jvm x -2147483648

+1
source

Java integers are signed and they overflow (both in C and in many other languages). Try this to test this behavior:

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

All Articles