
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 withi
equal to 1.Condition:
i <= 5
– The loop continues as long asi
is less than or equal to 5.Update:
i++
– The counteri
is incremented by 1 after each iteration.
Output:
12345
For 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 = 0
toi < numbers.length
(i.e., until the index reaches the length of the array).In each iteration, the element at index
i
is printed.
Output:
1020304050
For-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 : numbers
iterates over each element of thenumbers
array. The variablenum
will take the value of each element in the array during each iteration.
Output:
1020304050
Nested 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
i
andj
.
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
break
statement can be used to exit the loop prematurely.continue: The
continue
statement 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:
1234
Example 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:
1234678910
Conclusion
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! ?