For Loop Statement in Java

In Java, looping statements are used to execute instructions repeatedly when your program meets a certain condition or evaluates to true.

In this tutorial, we will be looking at the for-loop statement.

Java provides many different ways to loop your statements.

1. For Loop Statement

Syntax:

for( initialization; condition; incr/decr){  
//code to be executed  
}
  • initialization – variable initialization takes place.
  • condition – It executes each time to make the decision until the condition meets false.
  • increment/decrement – it increments or decrements the initialized variable for the next iteration.

Example:

public class DemoClass {
	public static void main(String[] args) { 
		
		for (int i = 1; i <= 10; i++) {
			System.out.println(i);
		}
	}
}

This program will print numbers from 1 to 10 because the value of the variable i is starting from 1 and will be going up to <=10. Therefore, for-loop will execute based on the condition i.e 10 times.

Output:

1
2
3
4
5
6
7
8
9
10

2. Nested For Loop Statement in Java:

It means when we have for-loop inside another for-loop that is called nested for-loop. Nested for-loop executes whenever outer loop executes.

Syntax:

for ( initialization; condition; increment ) {
//outer for-loop
   for ( initialization; condition; increment ) {
       // nested for-loop
      // code to be executed
   }
   // code to be executed
}

Example:

public class DemoClass {
	public static void main(String[] args) {
		// loop of a
		for (int a = 1; a <= 3; a++) {
			// loop of b
			for (int b = 1; b <= 3; b++) {
				System.out.println(a + " " + b);
			} // end of a
		} // end of b
	}
}

I hope you’ve understood for loop statement in Java.