Java for Loop



In this tutorial, we will learn how to use the for loop in Java with the help of examples.

Loops are used to repeat a block of code. For example, if we want to display a message 10 times, we can use a loop rather than typing the same code 10 times.


Java for Loop

Java for loop is used to repeat a specific block of code for a certain number of times.

The syntax of the Java for loop can be given as follows:

for(initialization; condition; updation) {
    // body of the loop 
}

Here,

  • initializationExpression - It initializes or declares variables and executes only once.
  • condition - The condition is evaluated. If it is true, the body of the for loop is executed.
  • updateExpression - It updates the value of the initialization expression. It is executed every time after the code block has been executed.

The following example will print the numbers 0 to 5:

public class Main {
    public static void main(String[] args) {

        for(int i = 0; i < 6; i++) {
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4
5

Example explained

  • int i = 0 - It sets a variable before the loop starts.
  • i < 6 - It defines the condition for the loop to run. If the condition is true, the loop will start over again. If it is false, the loop will end.
  • i++ - It increases the value each time the code in the loop is being executed.

Flowchart of Java for Loop

The following illustration shows how the Java for loop works.

Flowchart of the Java for Loop

Example: Display a Text Three Times

In the following example, we will display a text three times.

public class Main {
    public static void main(String[] args) {
        
        int n = 3;
        for(int i = 0; i < n; ++i) {
            System.out.println("Hello World");
        }
    }
}

Output:

Hello World
Hello World
Hello World

Here is how the above program works.

Iteration Variable Condition: i < n Action
1st i = 0 n = 3 true Hello World is printed. i is increased to 1.
2nd i = 1 n = 3 true Hello World is printed. i is increased to 2.
3rd i = 2 n = 3 true Hello World is printed. i is increased to 3.
4th i = 3 n = 3 false The loop is terminated.

Example: Calculate the Sum of n Natural Numbers

In the following example, we will calculate the sum of n natural numbers.

public class Main {
    public static void main(String[] args) {
        
        int sum = 0;
        int n = 500;

        for(int i = 1; i <= n; ++i) {
            sum += i;
        }

        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 125250

In the above program, the value of sum is initialized to 0. The for loop is iterated from i = 1 to 500. In each iteration, i is added to sum, and its value is increased by 1.

When i becomes 501, the test condition is false and sum will be equal to 0 + 1 + 2 + 3 + ... + 500.


Java for-each Loop

Java offers an alternative syntax of the for loop to make it easy to iterate through arrays and collections. For example,

public class Main {
    public static void main(String[] args) {
        
        // create an array
        int[]  numbArray = {17, 5, 28, 7, 43, 85};

        // using for-each to iterate though the array
        for(int numb : numbArray) {
            System.out.println(numb);
        }
    }
}

Output

17
5
28
7
43
85

Above, we have used the for-each loop to display each element of the numbArray array one element by one.

In the first iteration of the loop, numb will be 17, then 5 in the second iteration, and so on.

To learn more, you can visit Java for-each Loop


Java Infinite for Loop

In Java, creating an infinite loop can be made by setting the test condition in a way that it never evaluates to false. For example,

public class Main {
    public static void main(String[] args) {
        
        int sum = 0;
        
        for(int i = 0; i <= 5; --i) {
            System.out.println("Hello World");
        }
    }
}

In the above program, the test condition, i <= 5, is never false, and Hello World is printed repeatedly until the memory runs out.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.