for loop in Java

      No Comments on for loop in Java




for loop provides a way for initialization , testing condition and incrementing / decrementing in a single line. It is a concise way of doing it.

Generally, for loop is used when you know in advance how many times the loop is going to run.

for(initialization;testing condtion;increment/decrement statement) {

   // Body of for loop which is executed till the time condition evaluates to true.

}

Let us take an example to illustrate for loop in java :

package com.masterjavatutorial;

public class Main {

	public static void main(String[] args) {
		for(int i=0 ; i<10; i++){
			System.out.println("Value of i = "+i); 
		}
		
		System.out.println("################");
		
		int i =0;
		for(;i<10;){
			System.out.println(" i = "+i);
			i++;
		}
		
	}
	
}

The output of the above program is as below:

Value of i = 0
Value of i = 1
Value of i = 2
Value of i = 3
Value of i = 4
Value of i = 5
Value of i = 6
Value of i = 7
Value of i = 8
Value of i = 9
################
 i = 0
 i = 1
 i = 2
 i = 3
 i = 4
 i = 5
 i = 6
 i = 7
 i = 8
 i = 9

What is the logic Behind for loop execution:

First the variable is intialized and then the condition is tested for that variable. If it evaluates to true, then the code inside for loop is executed otherwise it exits the loop. After the execution, control return to increment/decrement condition. The variable is incremented or decremented according to the logic written and then again the condition is checked and if it evaluates to true , then the code inside for loop is executed otherwise it exits the loop.

Different Forms of for loop :

All the below forms of for loop are valid.

1.) for(int i=0 ; i<10; i++)

2.) int i=0;
for(; i<10; i++)

3.) for(;;) --- This is an infinite loop.THis for loop can have body also which will execute infinite number of times. Any code written after and outside this loop will become unreachable and will give compile time errors.






Leave a Reply