
In Java For Loop is used to repeat a particular block of code a definite number of times. Despite the while loop which is used until a condition evaluates to true the for loop is used to repeat a group of statements for a definite range. In this article, let us understand the workings of Java For Loop clearly.
| for(initial; condition; update) { // Code to be executed in each iteration } |
Where,
Initial: It defines the starting point of the for loop
Condition: it specifies the condition up to which the loop is supposed to run
Update: This is an increment or decrement operator based on the condition which updates after each iteration.
| public class ArrayTraversal { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } } } |
In the above code, the for loop iterates through each element in an array which is of size 5. The numbers. length calculates the size of the array and the loop starts iteration from 0 index to the size of the array.
The increment operator (++) is used to move to the next step in the iteration. Each iteration is printed on the screen until the conditions are met and the for loop is stopped.
| import java.util.ArrayList; public class ForEachListExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); for (String fruit: fruits) { System.out.println(fruit); } } } |
In this, for each loop, you need not mention three statements to run the loop. You will only need to write the name of the array and the “ for each” loop will run through each element in the array.
| for (initial; condition; update) { for (initial; condition; update) { // Code to execute inside the inner loop } } |
| public class NestedForLoop { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { // Outer loop for (int j = 1; j <= 3; j++) { // Inner loop System.out.print(i + "," + j + " "); } System.out.println(); // Moves to the next line } } } |

| public class BreakExample { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { // Breaks the loop when i is 5 System.out.println("Loop terminated at i = " + i); break; } System.out.println("i = " + i); } System.out.println("Outside the loop"); } } |

| public class ContinueExample { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { // Skips the iteration when i is 5 System.out.println("Skipping i = " + i); continue; } System.out.println("i = " + i); } } } |

| * * * * * * * * * * |