Krivalar Tutorials 
Krivalar Tutorials

Java for loop in programming


<<Previous

Next >>





for statement

for statement - Syntax

for(initialization statement;
		termination statement that returns true or false;
		loop counter){
	statement;
}

for statement - Example


public class ForLoop {
public static void main(String a[]){
	for(int i=0; i<10;i++)
	{
		System.out.print("" + i + ",");
	}
}
}

The above for loop prints

0,1,2,3,4,5,6,7,8,9,

In the above for loop:

int i=0 - is the initialization statment
i<10 - is the termination statement based on which the block executes if the condition returns true
i++ - is the loop counter and it is an expression that can be used to modify the values in the termination statement.

This statement can be increment or decrement or any other evaluation.


for loop can work without initialization statement

public class ForLoopNoInitialization {
public static void main(String a[]){
	int i=0;
	for(;i<10;i++)	{
		System.out.print(
			"" + i + ",");
	}
}
}
Above code will print:
0,1,2,3,4,5,6,7,8,9,

for loop can work without termination statement, in which case, you have to take care of terminating the loop using break statement or any other way.


public class ForLoopNoTermination {
public static void main(String a[]){
	int i=0;
	for(;;i++){
		System.out.print("" + i + ",");
		if(i>=10){ break; }

	}
}
}
Above code will print:
0,1,2,3,4,5,6,7,8,9,
for loop can work without loop counter statement in which case you need to find a way to run the loop for different values.

public class ForLoopNoInitNoConditionNoTermination {
public static void main(String a[]){
	int i=0;
	for(;;){
		if(i>=10){
			break;
		}
		System.out.print("" + i + ",");
		i++;
	}
}
}
This will print:
0,1,2,3,4,5,6,7,8,9,


<<Previous

Next >>