Java For Loop

The Java For loop is used to repeat a block of statements with the given number of times until the given condition is False. The for loop is one of the most used ones in any programming language and let us see the syntax:

In the Java for loop, there are three expressions separated by the semi-colons (;) and the execution of these expressions is as follows:

  • Initialization: It starts with the initialization statement. So, counter variables are initialized first (Example counter = 1 or i = 1). The initialization section is executed only once at the beginning.
  • Test Condition: The value of the counter variable will be tested against the test condition. If the result evaluates to True, the compiler will execute the statements inside the body of the for loop. If the condition is false, it will terminate.
  • Increment and decrement operator: This expression will run after the end of each iteration. This operator helps to increase or decrease the counter variable of the for loop as per our requirement.

Java For loop Syntax

The syntax of the For Loop in this Programming language is as follows:

for (initialization; test condition; increment/decrement operator)  {
       Statement 1
       Statement 2
       ………
       Statement n
}

Java For Loop initialization

The For loop has the flexibility to omit one or more sections from the declaration. Although we can skip one or more sections from the declaration, we must put the semicolon (;) in place; otherwise, it will throw a compilation error.

Initialize the counter variable can skip from for loop, as shown below:

int i = 1;

for( ; i <= 20; i++)

If you observe the above code snippet, the counter variable is declared in the previous line. Like the initialization condition, we can also skip the increment part of the For loop.

int i = 1;

for( ; i <= 10; )  {
    //statements     
    i++;
}

If you observe the above Java for loop code snippet, the increment part is declared in the body. It also allows us to initialize more than one counter variable at a time with comma separate:

for(i = 1,j = 10; i < j; i++)

The For loop also allows using multiple conditions. Instead of using a comma, we have to use the logical operator to separate the two conditions.

for(i=1,j=20; i <= 10 && j >= 20; i++) {
   //statements
   j++;
}

Like the test condition, Java for loop allows us to use more than one increment operator as follows. Please refer to the Java tutorial page.

for(i = 1, j = 1; i <= 10 && j <= 10; i++, j++)

Infinite For loop

for( ; ; )

The increment and decrement operator section initialization uses a comma to separate multiple declarations. To separate the test conditions, you must use logical operators to join conditions.

For loop Flow Chart

The screenshot below will show the flow chart of For Loop in Java Programming language.

For Loop FLOW CHART

The execution process of the for loop is:

  1. Initialization: We initialize the counter variable(s). We use the assignment operator for initialization purposes.
  2. Test condition: It will check the condition against the counter variable. If the condition is True, the compiler will execute the statements inside. If the condition is False, then it will exit. Here, we utilize the Java relational operators for comparison.
  3. After completing the iteration, it will execute the Increment and Decrement Operator inside the Java for loop to increment or decrement the value.
  4. Again it will check the expression after the value is incremented. The statements inside this will execute as long as the condition is true.

Java For Loop example

This Java program allows the user to enter any integer values. Then it will calculate the sum of natural numbers up to the user’s entered number using the for loop.

package Loops;

import java.util.Scanner;

public class ForLoop {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int i, number, sum = 1;
		sc = new Scanner(System.in);	
		
		System.out.println("\n Please Enter the any integer Value: ");
		number = sc.nextInt();
		
		for (i = 1; i <= number; i++)  {
			sum = sum * i;
		}
		System.out.format(" Sum of the Numbers From the is: %d ", sum);
	}
}
Java For Loop Example

TIP: Please refer to the Java while loop, Java do-while loop, and Java nested loops articles for more information on loops.

The first statements in this program will ask the user to enter any integer value below 10. Next, we assign the user entered value to the integer variable (number)

Next line, we use the Java For loop, and the Condition inside it will make sure that the value of i is less than or equal to the user-specified Number.

for(i = 1; i <= number; i++)  {
	sum = sum * i;
}

In this example, User Entered value: Number = 5 and we initialized the sum = 0

First Iteration: Within this, we initialized the i value as 1. Remember, Initialization happens only once. Next, the compiler will check the expression (i <= number), which is TRUE. So, the statement or block of code inside it will execute.

sum = sum * i

sum = 1 * 1 ==> 1

Next, i value will incremented by 1 (i++). Please refer to the Java Increment and Decrement Operators article to understand this ++ notation.

Java for loop Second Iteration: Within the first Iteration, the values of i changed as i = 2. Next, it will evaluate the condition (i <= number), which is TRUE. So, the statement inside it will execute.

sum= 1 * 2 = 2

Next, the number will increment by 1 (number ++).

Third Iteration: Within the second Iteration, the values of both i and sum changed as i = 3 and sum = 2. Next, the compiler will check the condition (i <= number), which is TRUE.

sum = 2 * 3 = 6

Fourth Iteration: Within the third Iteration, the values of i = 4 and sum = 6. Next, the compiler will check the condition (i <= number), which is TRUE. So, the statement inside it will execute.

sum = 6 * 4 = 24

Fifth Iteration: Within the fourth Iteration, the values of i = 5 and sum = 24.

sum = 24 * 5 = 120

I = 6. So, the condition present in the code ( 6 <= 5) evaluates to false.

The last System statement will print the number of digits present in the given number as output.

NOTE: We can use the break statement and continue statement to break the execution of the for loop iteration or to stop the current iteration. Check the Java break and Java continue statements.

Java for loop with multiple variables

The for loop allows you to use multiple variables in its syntax. To demonstrate it, we use the gaming example. In the following program, we use multiple variables in the for loop initialization, a single condition, and multiple variables in the increment.

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

for (int level = 1, score = 1;level <= 5;level++, score *= 10) {
System.out.println("Current Level = " + level + ", Score = " + score);
}
}
}
Current Level = 1, Score = 1
Current Level = 2, Score = 10
Current Level = 3, Score = 100
Current Level = 4, Score = 1000
Current Level = 5, Score = 10000

Java for loop list

We can use the for loop to iterate over a list of any data type. In the example below, we declared a list of strings that holds five popular movies. Next, we used the modern for loop approach to print those movies in the order they were saved.

import java.util.Arrays;
import java.util.List;

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

List<String> movies = Arrays.asList(
"Avatar",
"RRR",
"Avengers",
"Dark Knight",
"Bahubali");

for (String name : movies) {
System.out.println(name);
}
}
}
Avatar
RRR
Avengers
Dark Knight
Bahubali

If you want to use the traditional for loop with counter increment approach, use the following code. Replace the for loop in the above program with this.

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

Java for loop array

We can use the traditional for loop with initialization, condition, and counter-update syntax to iterate over array elements, or use a modern approach. It does not require a condition or counter value updates. All we have to do is initialize the variable (int, String, etc.) based on the array type. Next, use a colon, then the array name.

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

String[] movies = {"Avatar","RRR","Dark Knight","Avengers"};
for (String name : movies) {
System.out.println(name);
}
}
}
Avatar
RRR
Dark Knight
Avengers

Java for loop array length

If we want to use the traditional for loop approach to iterate over array items, we must use the array length property inside a for loop. In the example below, we declared a numeric array of five elements. Refer to the Java array article.

Next, the for loop starts iteration from 0, which is the index position of the first array element. The condition uses the length property to find the length of an array (5) and subtracts 1 from it to get the last index position. Next, increment the index position on each iteration.

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

int[] numbers = {12, 24, 36, 48, 60};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
12
24
36
48
60

Java for loop infinite

When working with a for loop, we must be careful with infinite looping. If we miss any part of the syntax (initialization, condition, increment/decrement), it leads to an infinite loop.

In the example below, we used a for loop without initialization, condition, or increment/decrement, so it runs forever.

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

for (;;) {
System.out.println("It runs endless times");
}
}
}

In the example below, we initialized the value of i to 0, and on each iteration, i is incremented by 1. However, there is no condition to check, and the for loop never stops (runs infinitely).

for (int i = 0;;i++) {
System.out.println("It runs endless times");
}

The program below has no increment/decrement section, so I is always 0, and the condition (I <= 10) always returns true, so the for loop runs infinitely.

for (int i = 0;i <= 10;) {
System.out.println("It runs endless times");
}

It is a classic example of an infinite loop because users think they met the syntax rule. However, the condition and the increment/decrement operator run in opposite directions.

For instance, the program below requires the for loop to print numbers from 0 to 10. So, the iteration started at 0, and the condition (i <= 10) kept the for loop from exceeding 10. However, on each iteration, instead of incrementing the value, we used (i–), decrementing it. So, the value of I never reaches 10 (not even 1) because it returns -1, -2, etc.

for (int i = 0;i <= 10; i--) {
System.out.println("It runs endless times" + i);
}

Fix the Java for loop infinite issue

Always use the initialization, condition, and increment/decrement of a for loop. The counter variable (i) should be incremented or decremented to meet the condition. For example, to move forward, use i++ and to move backward, use i–.

How to loop backwards using a Java for loop?

The for loop allows us to use the decrement operator to loop backwards. For instance, if we specify i++, the loop moves forward by a single position. However, if we set as i–, the loop moves backwards by a single position.

In the following example, we declared an array of four elements. Next, the for loop iteration starts at the last index position. To get this position, we used the length and subtracted one because array element indices are between 0 and n-1.

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

int[] numbers = {10, 20, 30, 40};
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println(numbers[i]);
}
}
}
40
30
20
10

NOTE: We must always use length – 1, which points to the last value in an array. However, if we use numbers.length, the program will return an ArrayIndexOutOfBoundsException.

Java for loop custom increment (step 2)

A for loop allows you to use the increment or decrement operator to increase or decrease the current value by 1 to move forward or backward. However, we can use the Java Arithmetic Operators or Java Assignment Operators to custom increment the value.

For example, the following program returns alternative numbers (odd) between 1 and 10. Here, we used i += 2. It means that on each iteration, the value of i is incremented by 2 (instead of 1).

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

int number = 10;
for (int i = 1; i <= number; i+= 2) {
System.out.print(i + " ");
}
}
}
1  3  5  7  9 

Similar to the above, the following program performs the for loop with a custom increment of 10. On each for loop iteration, the value of i is incremented by 10.

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

int number = 100;
for (int i = 1; i <= number; i+= 10) {
System.out.print(i + " ");
}
}
}
1  11  21  31  41  51  61  71  81  91