for Keyword in Java
The for
keyword in Java is used to create a loop that repeatedly executes a block of code a specified number of times. It is one of the most commonly used control flow statements for iterating over arrays, collections, or ranges of values.
Usage
The for
loop is ideal for scenarios where the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.
Syntax
for (initialization; condition; increment/decrement) {
// Code to be executed
}
initialization
: Initializes the loop control variable.condition
: Evaluated before each iteration; the loop continues as long as this condition is true.increment/decrement
: Updates the loop control variable after each iteration.
Examples
Example 1: Basic For Loop
public class BasicForLoop {
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 increments i
by 1 after each iteration. The loop prints the value of i
for each iteration.
Example 2: For Loop with Array
public class ForLoopWithArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Number: " + numbers[i]);
}
}
}
This example demonstrates iterating over an array using a for
loop. The loop runs from i = 0
to i < numbers.length
, printing each element of the numbers
array.
Example 3: Enhanced For Loop
public class EnhancedForLoop {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}
The enhanced for
loop, also known as the "for-each" loop, simplifies the iteration over arrays and collections. In this example, it iterates over the fruits
array and prints each fruit.
Example 4: Nested For Loop
public class NestedForLoop {
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);
}
}
}
}
This example illustrates a nested for
loop where an outer loop runs from 1 to 3, and an inner loop also runs from 1 to 3. The inner loop completes all its iterations for each iteration of the outer loop.
Tips and Best Practices
- Initialization: Declare and initialize the loop control variable within the
for
statement to limit its scope to the loop. - Condition: Ensure the loop condition will eventually become false to avoid infinite loops.
- Increment/Decrement: Properly update the loop control variable to ensure the loop progresses towards termination.
- Enhanced For Loop: Use the enhanced
for
loop for better readability when iterating over arrays or collections.for (ElementType element : collection) { // Code to be executed }
- Avoid Modifying Collection: When using the enhanced
for
loop, avoid modifying the collection being iterated to preventConcurrentModificationException
. - Performance Considerations: In performance-critical applications, consider the overhead of additional operations within the loop, and optimize accordingly.
- Infinite Loop: To create an infinite loop, you can omit the condition in the
for
statement:for (;;) { // Infinite loop code }