A for loop in java has the following structure -
for (initialization statement; condition check; update) loop body;
As you can see, there are four statements here -
- Initialization operator: this statement is executed only once when the cycle is entered for the first time. This is an optional statement, that is, you can leave this field empty. It is commonly used for some initialization purposes.
- Conditional Verification: This statement is probably the most important. It checks to see if a particular expression matches the true one. If so, the loop continues. You can leave this field blank, which will be evaluated as
true . - Update: this list of statements runs from left to right, usually used to increase / decrease a variable.
- loop body: the loop body that will be executed again and again based on the conditional value of the validity of the check.
Basically, this is what execution looks like: firstly, when a cycle is entered for the first time, the initialization statement is executed once. A conditional check is then performed to check if it is true. If so, then the body of the loop is executed, otherwise the loop is completed. After that, the () update statements are executed. Next, the conditional check is performed again, and if it evaluates to true, then the loop body is executed again, then the update instruction is executed, then the conditional check again .... you get the image.
Now about the syntax for( ; ; ) . It has no initialization instruction, so nothing will be executed. This conditional check statement is also empty, so it means that it evaluates to true. After that, the loop body is executed. Then, since the update statement is empty, nothing is executed. Then a conditional check is performed, which is again evaluated as true, and then the whole process will be repeated again.
So you see that this is basically an endless loop that does not have an initialization instruction, whose conditional check always evaluates to true and does not have an update statement. It is equivalent to -
while(true) { ..... }
which is another popular loop construct in java.
When you use an infinite loop like this, it is important to pay attention to the interrupt condition, since in most cases you cannot let the loop run indefinitely. To break out of these types of loops, you can use the break statement. The structure is as follows:
if(some_condition_is_true) break; // This will cause execution to break out of its nearest loop
or
if(some_condition_is_false) break;