English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java topics

Java for Loops

In this tutorial, we will learn how to use the for loop in Java with examples, and we will also learn how the for loop works in computer programming.

In computer programming, loops are used to repeat a specific code block until a certain condition is met (the test expression is false). For example,

Imagine that we need to print a sentence on the screen50 times. Well, we can use the print statement50 times (without using loops) to do this. How about printing a million sentences? At this point, you need to use a loop. With a loop, we can write the print statement only once and then run it any number of times.

This is just a simple example that shows the importance of loops in computer programming.

Java for Loops

The syntax of the for loop in Java is:

for (initialization; testExpression; update)
{
    // The code inside the loop
}

The work of the for loop

  1. Initialization(initialization) expression is executed only once.

  2. Then, evaluateTestExpression (testExpression). Here, the test expression (testExpression) is a boolean expression.

  3. If the calculation result of the test expression (testExpression) is true, execute the code within the for loop.

  4. Then executeUpdateexpression (update).

  5. Again, evaluate the test expression (initialization).

  6. If the test expression is true, execute the code within the for loop and continue to execute the update expression (update).

  7.             This process continues until the test expression (testExpression) is evaluated as false.

  8. If the calculation result of the test expression (testExpression) is false, the for loop terminates.

for loop flowchart

for loop workflow diagram

Example1: for loop

//The program prints a sentence ten times
class Loop {
    public static void main(String[] args) {
      
        for (int i = 1; i <= 10; ++i) {
            System.out.println("Line " + i);
        }
    }
}

Output:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

In the above example, we have

  • Initialization expression: int i = 1

  • Test expression: i <= 10

  • Update expression:++ i

Here, the initial value of i is1. Therefore, the test expression is initially true. So, the print statement will be executed. Now, evaluate the update expression.

Each time the update expression is evaluated, the value of i increases1. Again, evaluate the test expression.

This process continues until i is11. When i is11when 10)is false, the for loop terminates.

For more information about test expressions and their evaluation methods, please visitRelational operatorsandLogical operators.

Example2: for loop

//The program finds the sum of natural numbers from1to1000. The sum of natural numbers up to
class Number {
    public static void main(String[] args) {
      
        int sum = 0;
	   
        for (int i = 1; i <= 1000; ++i) {
            sum += i;     //is equivalent to sum = sum + i
        }
	   
        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 500500

Here, we have a variable named sum. Its initial value is 0. Inside the for loop, we initialized a variable named i with the value of1.

In each iteration of the for loop,

  • Assign a value to the sum variable: sum + i

  • the value of i increases1

the loop continues until the value of i is greater than1000. To achieve better visualization effects,

1 repeat: i = 1 simultaneously sum = 0+1 = 1
2 repeat: i = 2 simultaneously sum = 1+2 = 3
3 repeat: i = 3 simultaneously sum = 3+3 = 6
4 repeat: i = 4 simultaneously sum = 6+4 = 10
... .. ...
999 repeat: i = 999 simultaneously sum = 498501 + 999 = 499500
1000 repeat: i = 1000 simultaneously sum = 499500 + 1000 = 500500

Infinite Loop

We should always be careful when using loops. This is because if we incorrectly set the test expression to never be false, the for loop will run indefinitely.

This is called an infinite loop. For example,}}

//Infinite Loop
class Infinite {
    public static void main(String[] args) {
      
        int sum = 0;
        for (int i = 1; i <= 10; --i) {
            System.out.println("Hello");
        }
    }
}

Here, the test expression (i <= 10) will never appear false, and hello will print infinitely (at least in theory).

for (; ; ) {
}

Java for-each loop (traversal loop)

In Java, another syntax for the for loop can be used forJava ArraysandJava Collections(also known as a traversal loop). For example,

for (int a : array) {
    System.out.println(a);
}

For more information, please visit:Java Traversal Loops