Java For Loop

The for loop repeatedly executes a block of statements until a particular condition is true.

Syntax

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for( initialization; condition; statement){
//Block of statements
}
for( initialization; condition; statement){ //Block of statements }
for( initialization; condition; statement){ 
        //Block of statements
}

 

Where:

  • initialization statement: is used to initialize the loop variable.
  • boolean expression: is used for condition check whether returns true or false.
  • statement: is used for either increment or decrement of the loop variable.

 

Program to use for loop example in java.

 

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class ForLoopExample {
static void forLoopTest(int num){
//For loop test
for(int i=1; i<= num; i++){
System.out.println(i);
}
}
public static void main(String args[]){
//method call
forLoopTest(10);
}
}
public class ForLoopExample { static void forLoopTest(int num){ //For loop test for(int i=1; i<= num; i++){ System.out.println(i); } } public static void main(String args[]){ //method call forLoopTest(10); } }
public class ForLoopExample {	
	static void forLoopTest(int num){
		//For loop test
		 for(int i=1; i<= num; i++){             
			 System.out.println(i);            
                 }
	}	
	
	public static void main(String args[]){ 
		//method call 
		forLoopTest(10); 
	}
}

Output

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
4
5
6
7
8
9
10
1 2 3 4 5 6 7 8 9 10
1
2
3
4
5
6
7
8
9
10