Website For Developers

For loop in Java


In java, there are three types of loops.


For loop in Java

Syntax

for (initialization; condition/check; increment/decrement) {
// for loop body
}

Initialization

Condition

increment/decrement


Example of for loop in Java

public class ForLoop {

   public static void main(String[] args) {
     int count = 0;
     for (count = 0; count < 5; count++) {
       System.out.println( "count: "+ count);
     }
   }
}

Output

count: 0
count: 1
count: 2
count: 3
count: 4



Enhanced for loop / For-each loop in Java

Syntax

for (declaration : expression){
//loop body
}


Example of foreach loop in Java

public class ForEachLoop {

   public static void main(String[] args) {
     int [] numbers = {1,2,3,4,5};
     for (int i : numbers) {
       System.out.println(i);
     }
   }
}

Output

1
2
3
4
5