The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
There are three types of for loop in java.
- Simple For Loop
- For-each or Enhanced For Loop
- Labeled For Loop
Java Simple For Loop
The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.
Java For-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Java Labeled For Loop
We can have name of each for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop.
Normally, break and continue keywords breaks/continues the inner most for loop only.
If you use break bb;, it will break inner loop only which is the default behavior of any loop.
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Now, you need to press ctrl+c to exit from the program.