Why this loop is not infinite

Eagle_Eye :

Can somebody direct me to right path for

Why in the following code, there is a gap of a second between start and end msg?

System.out.println("Start:" + LocalTime.now());
for (int i = 0; i > -1; i++) { /*Infinite loop*/ }
System.out.println("End  :" + LocalTime.now());

I tried to find out if DCE takes time for this type of code but couldn't find much.

devm :

As you have defined "i" as int which ranges from -2,147,483,648 to 2,147,483, 647. As soon as it reaches -2147483648 (your code loops starting from 0 and increment 1) , the condition becomes false and the loop breaks.

    int i;
    System.out.println("Start: " + LocalTime.now());
    for (i = 0; i > -1; i++) { /*Infinite loop*/ }
    System.out.println("End  :" + LocalTime.now());
    System.out.println("i  :" + i);

Try above and you will see the value at the end is -2147483648 and hence it comes out of the loop.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99259&siteId=1