Skip to main content

For Loop in Java

  • A for loop is used to iterate over a block of code a specific number of times.

  • It's commonly used for counting iterations, traversing arrays, and managing repetitive tasks.

  • It is a fundamental control structure in Java that allows you to execute a block of code repeatedly.

  • The for loop is particularly useful when you know in advance how many times you want to execute a statement or a block of statements.

Syntax of a for Loop

Here is the basic syntax of a for loop in Java:

for (initialization; condition; update) {
// code to be executed
}
  • initialization: This is executed once at the beginning of the loop. It's usually used to initialize a counter variable.

  • condition: This is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop terminates.

  • update: This is executed after each iteration of the loop. It's usually used to update the counter variable.

How It Works

  • Initialization: The initialization step is executed first and only once. It sets the starting value of the counter variable.

  • Condition: Before each iteration, the condition is checked. If it's true, the loop body is executed. If it's false, the loop terminates.

  • Loop Body: The block of code inside the curly braces {} is executed.

  • Update: After the loop body is executed, the update step is executed. This typically increments or decrements the counter variable.

This process repeats until the condition evaluates to false.

Example of a for Loop

Let's look at a simple example to understand how a for loop works. Consider the following code:

public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
}
}

Explanation:

  • Initialization: int i = 0; initializes the counter variable i to 0.

  • Condition: i < 5 is the condition that is checked before each iteration. The loop will continue to execute as long as i is less than 5.

  • Loop Body: System.out.println("Iteration: " + i); prints the current value of i to the console.

  • Update: i++ increments the counter variable i by 1 after each iteration.

Since i starts at 0 and increments by 1 each time, the loop will run 5 times, producing the following output:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

More Detailed Breakdown

1. First Iteration:

  • Initialization: int i = 0;

  • Condition: i < 5 (true)

  • Loop Body: Prints "Iteration: 0"

  • Update: i++ (i becomes 1)

2. Second Iteration:

  • Condition: i < 5 (true)

  • Loop Body: Prints "Iteration: 1"

  • Update: i++ (i becomes 2)

3. Third Iteration:

  • Condition: i < 5 (true)

  • Loop Body: Prints "Iteration: 2"

  • Update: i++ (i becomes 3)

4. Fourth Iteration:

  • Condition: i < 5 (true)

  • Loop Body: Prints "Iteration: 3"

  • Update: i++ (i becomes 4)

5. Fifth Iteration:

  • Condition: i < 5 (true)

  • Loop Body: Prints "Iteration: 4"

  • Update: i++ (i becomes 5)

6. Termination:

  • Condition: i < 5 (false)

  • The loop terminates.

Using a for Loop with Arrays

A common use of the for loop is to iterate through the elements of an array. Here's an example:

public class Main {
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]);
}
}
}

Explanation:

  • In Java, an array is a data structure that stores a fixed-size sequence of elements of the same type. We will discuss about array in further details.

  • Array Declaration: int[] numbers = {10, 20, 30, 40, 50}; declares an array of integers.

  • For Loop: Iterates over the array using the counter variable i.

  • Condition: i < numbers.length ensures the loop runs as long as i is less than the length of the array.

  • Accessing Array Elements: numbers[i] accesses the element at index i.

The output will be:

Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Enhanced for Loop (for-each)

Java also provides an enhanced for loop, also known as a for-each loop, which is used to iterate over arrays and collections.

Here’s an example:

public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

for (int number : numbers) {
System.out.println("Element: " + number);
}
}
}

Explanation:

  • Enhanced For Loop: for (int number : numbers) iterates over each element in the array numbers.

  • Variable number: Represents the current element in the array during each iteration.

The output will be:

Element: 10
Element: 20
Element: 30
Element: 40
Element: 50

Summary

  • for loop: Executes a block of code a specific number of times.

  • Syntax: for (initialization; condition; update) { // code }

  • Initialization: Sets the starting value of the counter variable.

  • Condition: Evaluated before each iteration; if true, the loop body is executed.

  • Update: Updates the counter variable after each iteration.

  • Use with Arrays: Commonly used to iterate through arrays and collections.

  • Enhanced for loop (for-each): Simplifies array and collection traversal.

The for loop is an essential tool for controlling the flow of your Java programs.