Java For Loop in Java
For Loop in Java
The for loop in Java is a control flow statement that allows code to be repeatedly executed based on a condition. It is typically used when the number of iterations is known beforehand. A for loop has three parts:
Initialization: The loop starts with an initial statement where the loop counter is initialized.
Condition: The loop runs as long as this condition is true.
Increment/Decrement: After each iteration, the counter is updated (incremented or decremented).
Syntax of the For Loop:
for (initialization; condition; update) { // Code to be executed in each iteration}Initialization: This step is executed once at the beginning of the loop. It is typically used to declare and initialize the loop counter.
Condition: This condition is evaluated before every iteration. If it evaluates to
true, the loop continues to execute. Iffalse, the loop stops.Update: This step is executed after each iteration. Typically used to increment or decrement the loop counter.
Basic Example of a For Loop
This example prints numbers from 1 to 5:
public class ForLoopExample { public static void main(String[] args) { // Loop starts at 1, runs while i is less than or equal to 5, and increments i by 1 in each iteration for (int i = 1; i <= 5; i++) { System.out.println(i); // Print the value of i in each iteration } }}Explanation:
Initialization:
int i = 1– Starts withiequal to 1.Condition:
i <= 5– The loop continues as long asiis less than or equal to 5.Update:
i++– The counteriis incremented by 1 after each iteration.
Output:
12345For Loop with Arrays
You can use a for loop to iterate over the elements of an array.
Example:
public class ForLoopWithArray { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; // Loop through the array and print each element for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } }}Explanation:
The loop runs from
i = 0toi < numbers.length(i.e., until the index reaches the length of the array).In each iteration, the element at index
iis printed.
Output:
1020304050For-each Loop (Enhanced For Loop)
Java also provides a simplified way to iterate over arrays and collections with the for-each loop.
Syntax:
for (datatype element : collection) { // Code to be executed with each element}Example:
public class ForEachLoopExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; // For-each loop to iterate through the array for (int num : numbers) { System.out.println(num); } }}Explanation:
int num : numbersiterates over each element of thenumbersarray. The variablenumwill take the value of each element in the array during each iteration.
Output:
1020304050Nested For Loop
A nested for loop is a loop inside another loop. This is useful when you need to perform multi-dimensional iterations, such as working with matrices or grids.
Example:
public class NestedForLoopExample { 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=" + i + ", j=" + j + " | "); } System.out.println(); // Move to the next line after each iteration of the outer loop } }}Explanation:
The outer loop runs three times (
i = 1, 2, 3), and for each iteration of the outer loop, the inner loop also runs three times (j = 1, 2, 3).The output shows all combinations of
iandj.
Output:
i=1, j=1 | i=1, j=2 | i=1, j=3 | i=2, j=1 | i=2, j=2 | i=2, j=3 | i=3, j=1 | i=3, j=2 | i=3, j=3 | Breaking and Continuing the For Loop
break: The
breakstatement can be used to exit the loop prematurely.continue: The
continuestatement skips the current iteration and proceeds with the next one.
Example with break:
public class BreakExample { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Exit the loop when i equals 5 } System.out.println(i); } }}Output:
1234Example with continue:
public class ContinueExample { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { continue; // Skip the iteration when i equals 5 } System.out.println(i); } }}Output:
1234678910Conclusion
The for loop is one of the most commonly used loops in Java and is helpful when the number of iterations is known ahead of time. You can use it for:
Iterating over arrays or collections.
Performing repetitive tasks a fixed number of times.
Handling nested iterations (e.g., 2D arrays or matrices).
Breaking or continuing the loop based on conditions.
Let me know if you'd like more detailed examples or explanations on any aspect of the for loop! ?