The Wayback Machine - https://web.archive.org/web/20250304004324/https://www.geeksforgeeks.org/java-for-loop-with-examples/
Open In App

Java For Loop

Last Updated : 15 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections.

Example:

Java
class Geeks {
  
    public static void main(String args[]) {
      
        // for loop to print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) {
          
            System.out.println("" + i);
        }
        
        System.out.println("Loop has ended.");
    }
}

Output
1
2
3
4
5
Loop has ended.

Dry-Running Above Example

  1. The program starts.
  2. The for loop initializes i to 1.
  3. Condition i <= 5 is checked.
    • If true:
      • Statement inside the loop executes, printing the current value of i.
      • Increment i by 1.
    • If false:
      • Loop terminates, and the program continues.
  4. Steps repeat until i becomes 6, at which point the condition fails, and “Loop has ended.” is printed.
For Loop in Java

Syntax

for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}

Working

  1. Control enters the for loop.
  2. Initialization is executed once at the beginning of the loop.
  3. The Condition is evaluated:
    1. If true, the control moves to Step 4.
    2. If false, the control jumps to Step 7.
  4. The body of the loop is executed.
  5. Control moves to the Updation step.
  6. After Updation, the flow returns to the Condition (Step 3) and repeats the process.
  7. Once the condition becomes false, the control exits the for loop, and statements outside the loop are executed.

Java for loop is divided into various parts as mentioned below:

  1. Initialization Expression
  2. Test Expression
  3. Update Expression

1. Initialization Expression

Initializes the loop variable. This is executed once at the start of the loop.

Example:  

int i = 1;

2. Test Expression

Tests the loop condition. If true, the loop body is executed; otherwise, the loop terminates.

Example:  

i <= 10

3. Update Expression

After executing the loop body, this expression increments/decrements the loop variable by some value. 

Example:  

i++;

Flow Chart

Flow chart for loop in Java


Example 1: Printing Numbers from 1 to 10

Java
// Java program to print numbers from 1 to 10
class GFG {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

Output
1
2
3
4
5
6
7
8
9
10

Example 2: Printing “Hello World” 5 Times  

Java
// Java program to illustrate for loop
class GFG {
    public static void main(String args[]) {
      
        // Writing a for loop
        // to print Hello World 5 times
        for (int i = 1; i <= 5; i++)
            System.out.println("Hello World");
    }
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World

Example 3: Calculating Sum from 1 to 20

Java
// Java program to calculate the 
// sum of numbers from 1 to 20
class GFG {
    public static void main(String args[]) {
        int s = 0;

        // for loop begins
        // and runs till x <= 20
        for (int x = 1; x <= 20; x++) {
            s = s + x;
        }
        System.out.println("Sum: " + s);
    }
}

Output
Sum: 210

Nested For Loop

Java Nested For Loop is a concept of using a for loop inside another for loop. It is commonly used for multidimensional problems.

Example: Printing a Matrix-like Pattern

Java
// Java program to illustrate 
// Nested For Loop
class GFG {
  
    public static void main(String[] args) {
      
        for (int i = 1; i <= 3; i++) {
          
            for (int j = 1; j <= 3; j++) {
              
                System.out.print("(" + i + "," + j + ") ");
            }
            System.out.println();
        }
    }
}

Output
(1,1) (1,2) (1,3) 
(2,1) (2,2) (2,3) 
(3,1) (3,2) (3,3) 

Note: To know more about Nested loops refer Nested loops in Java.

Java Infinite for Loop

An infinite loop occurs when the loop’s condition never becomes false. In the example below, the condition i >= 1 always evaluates to true, leading to an infinite loop.

Example 1:

Java
// Java Program to Illustrate 
// infinite loop
class GFG {
    public static void main(String args[])
    {
        for (int i = 1; i >= 1; i++) {
            System.out.println("Infinite Loop " + i);
        }
    }
}

Output:

Infinite Loop 1
Infinite Loop 2
...

Example 2: Another way to create an infinite loop is by using empty semicolons ;; in the for loop.

Java
public class GFG {
    public static void main(String[] args) {
      
        for (;;) {
            System.out.println("Infinite Loop");
        }
    }
}

Output:

infinitive loop
infinitive loop
....

Important Note: A “Time Limit Exceeded” error occurs when a program runs longer than the time allocated for execution, due to infinite loops.

Advantages of for Loop

  • This is ideal for iterating over a known range or collection.
  • Efficient syntax for initialization, condition checking, and incrementing.
  • Easy to control the number of iterations.
  • Efficient for looping through arrays and collections.

Kickstart your Java journey with our online course on Java Programming, covering everything from basics to advanced concepts. Complete real-world coding challenges and gain hands-on experience. Join the Three 90 Challenge—finish 90% in 90 days for a 90% refund. Start mastering Java today!


Next Article
Article Tags :
Practice Tags :

Similar Reads

Java for loop vs Enhanced for loop
In Java, loops are fundamental constructs for iterating over data structures or repeating blocks of code. Two commonly used loops are the for loop and the enhanced for loop. While they serve similar purposes, their applications and usage vary based on the scenario.for loop vs Enhanced for loopBelow comparison highlights the major differences betwee
4 min read
For-each loop in Java
The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.Example:Below is a basic example of using the for-each loop to iterate through
6 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Java Program to Reverse a Number and find the Sum of its Digits Using do-while Loop
Problem Statement: The number is supposed to be entered by the user be it any random number lying within the primitive data-type holding the number. First, the number needs to be reversed. Secondary the sum of the number is to be calculated with the constraint to use a do-while loop. do-while loop: Now the user sometimes does get confused between a
6 min read
Java Program to Find Sum of Natural Numbers Using While Loop
While loop arises into play where beforehand there is no conclusive evidence that how many times a loop is to be executed. This is the primary reason as there is no strict tight bound over how many numbers the sum is to be evaluated. Situations in which the output can be displayed using test condition abiding hardcoded outputs by simply running the
3 min read
Java Program to Compute the Sum of Numbers in a List Using For-Loop
Given a list of numbers, write a Java program to find the sum of all the elements in the List using for loop. For performing the given task, complete List traversal is necessary which makes the Time Complexity of the complete program to O(n), where n is the length of the List. Example: Input : List = [1, 2, 3] Output: Sum = 6 Input : List = [5, 1,
2 min read
Java Program to Compute the Sum of Numbers in a List Using While-Loop
The task is to compute the sum of numbers in a list using while loop. The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Approach Create a list.Create two in
2 min read
Perfect Number Program in Java Using While Loop
The number which is equal to the sum of its divisors is called a perfect number. Read the entered long number, assigned to the long variable n. While loop iterates until the condition (i<=n/2) is false. If the remainder of n/i=0 then add i value to the sum and increase the i value. After all the iterations compare the number with the sum, if bot
2 min read