Java For Loop
In this article, we are going to cover Java for loops with examples in the hope that you will learn something new. To repeat a block of code in computer programming, loops are used.
For Loop In Java
Java For loops are designed to iterate a part of the program repeatedly.
It is recommended to use a for loop if the number of iterations is fixed.
Instead of typing the same code 100 times, you can use a loop if you want to display the same message 100 times.
Use Java for loop instead of the while loop when you know exactly how many times you want to loop through a block of code:
Syntax:
for (statement 1; statement 2; statement 3) {
// block of code to be executed until the loop condition is false
}
Prior to the execution of the code block, statement 1 is executed (once).
The condition for executing the code block is defined by statement 2.
statement 3 is executed (every time) after the code block has been run.
Here is an example of printing the first 5 natural numbers:
Example: 
Similarly, we can also print the numbers in reverse order as shown in the example below:
Example: 
Example explained
In statement 1, a variable mrx is set before the loop starts (int mrx = 1).
Statement 2 defines the condition for running the loop (mrx must be less than or equal to 5). The loop will be restarted if the condition is true. The loop will end if it is false.
Whenever the code block in the loop is executed, statement 3 increases a value (mrx++).
Another Example
The following example will only print even numbers less than or equal to 10:
Example: 
The following example prints odd numbers till 20:
Example: 
For-Each Loop
Additionally, there is the “for-each” loop, which loops through array elements exclusively:
Syntax
for (type variableName : arrayName) {
// block of code to be executed
}
As an example, here is a “for-each” loop that outputs all the firms in an array:
Example: 
For Example, The names of the NFL teams can be printed by simply using the “for-each” loop.
Example: 
Reminder: It’s okay if you don’t understand the above example. In the Java Arrays chapter, you will learn more about arrays.
Nested Loops
A loop can also be placed inside another loop. In this case, we call them nested loops.
In each iteration of the “outer loop,” the “inner loop” will be executed once:
Example: 
Likewise, we have printed two arrays (multidimensional arrays) here by using a nested for loop to print the rank and name of the richest person in this world.
Example: 
Labeled For Loop in Java
There can be a name for each Java for loop. Labels are applied before the for loop to accomplish this.
We can break or continue specific for loops while using nested for loops.
Syntax:
labelname: for(initialization; condition; increment/decrement){ }
Example: 
A loop’s default behavior is to break the inner loop only if you use break ample:
Example: 
Having learned about java for loops, now you know what they are.