Java For Loop
The for
loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. It is particularly useful for iterating over arrays or collections and executing a block of code a specific number of times.
Syntax
for (initialization; condition; update) {
// Code to be executed
}
- initialization: Initializes the loop variable. It is executed once at the beginning of the loop.
- condition: Evaluated before each iteration. If
true
, the loop body executes; iffalse
, the loop terminates. - update: Updates the loop variable after each iteration.
Examples
Example 1: Basic for
Loop
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
In this example, the loop initializes i
to 0, checks if i
is less than 5, and prints the iteration number. After each iteration, i
is incremented by 1. The loop runs 5 times, printing values from 0 to 4.
Example 2: Iterating Over an Array
public class ArrayIterationExample {
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]);
}
}
}
This example demonstrates iterating over an array. The loop iterates through the numbers
array, using the index i
to access each element and print its value.
Example 3: Nested for
Loop
public class NestedForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
In this example, a nested for
loop is used to create a grid-like output. The outer loop iterates over i
, and for each iteration of i
, the inner loop iterates over j
. This results in a combination of all values of i
and j
.
Tips and Best Practices
- Initialization: Declare the loop variable within the
for
statement to limit its scope to the loop. - Readability: Keep the loop condition simple and easy to understand. Complex logic can be moved inside the loop body.
- Avoid Infinite Loops: Ensure the loop condition will eventually be
false
to prevent infinite loops. - Use Enhanced
for
Loop: For iterating over arrays or collections, consider using the enhancedfor
loop (also known as the "for-each" loop) for simplicity.
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
- Performance: Minimize the work done in the loop condition and update expressions to improve performance, especially in loops with a large number of iterations.