Java Tutorial-Java For Loop

Java For loop


When you know exactly how many times you want to loop through the block of code, use the for loop instead of while loop:


Syntax

for (statement 1; statement2; statement3){
                // code block to be executed
}

  • Statement 1 is executed one time before the execution of the code block.
  • Statement2 defines the condition which is checked every time for executing the code block.
  • Statement3 is executed every time after the code block has been executed.


Example

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

Output

0
1
2
3
4

Example explained


·         Here in the example, the initialization i=0, is executed only once when the loop gets started.

·         In the statement 2, the condition i<5 is executed every time to check whether the condition is true.

·         The statement3 increases a value (i++) every time the code block in loop has been executed.

 

The for-each loop


The for-each loop is exclusively used to loop through elements in an array.

Syntax

for(type variable: arrayname) {
                // code block to be executed
}

Example


To print each element in the “colors” array, we use a for-each loop

String colors[]={"red", "orange", "pink", "brown"};
for (String i : colors){
       System.out.println(i);
}

Output

red
orange
pink
brown