Last chance! 50% off DataCamp Premium
Sale ends in
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.
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.
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.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.
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.
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.
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.
for statement to limit its scope to the loop.for loop for better readability when iterating over arrays or collections.
for (ElementType element : collection) {
// Code to be executed
}
for loop, avoid modifying the collection being iterated to prevent ConcurrentModificationException.for statement:
for (;;) {
// Infinite loop code
}