Loops in Java
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 loops in Java.
Java Simple for Loop
ForExample.javaTest it Now
1 2 3 4 5 6 7 8 9 10
Java Nested for Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
Pyramid Example 1:
* * * * * * * * * * * * * * *
Pyramid Example 2:
* * * * * * * * * * * * * * * * * * * * *
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 the basis of elements and not the index. It returns element one by one in the defined variable.
ForEachExample.javaTest it Now
12 23 44 56 78
Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop.
Note: The break and continue keywords breaks or continues the innermost for loop respectively.
1 1 1 2 1 3 2 1
If you use break bb;, it will break inner loop only which is the default behaviour of any loop.
1 1 1 2 1 3 2 1 3 1 3 2 3 3
Java Infinitive for Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
infinitive loop infinitive loop infinitive loop infinitive loop infinitive loop ctrl+c
Now, you need to press ctrl+c to exit from the program.
Java for Loop vs while Loop vs do-while Loop