A loop does not stop executing immediately when its condition evaluates to true. A loop’s condition is evaluated at the start of a loop, meaning when the loop starts for the first time or the execution of a previous iteration of the loop body has just finished.

int number = 1;

while (number != 2) {
    System.out.println(number);
    number = 2;
    System.out.println(number);
    number = 1;
}

Even though number equals 2 at one point, the loop runs forever.

The condition of a loop is evaluated when the execution of a loop starts and when the execution of the loop body has reached the closing curly bracket. If the condition evaluates to true, execution continues from the top of the loop body. If the condition evaluates to false, execution continues from the first statement following the loop.

for (int i = 0; i != 100; i++) {
    System.out.println(i);
    i = 100;
    System.out.println(i);
    i = 0;
}

The loop above never stops executing.

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee