Java For Loop

In programming languages, looping is a feature which facilitates the execution of a set of instructions until the controlling Boolean-expression evaluates to false.

Java provides different types of loops to fit any programming need. Each loop has its own purpose and a suitable use case to serve.There are three types of loops in java.

  • for loop
  • while loop
  • do-while loop
Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.

There are three types of for loops in java.

  • Simple For Loop
  • For-each or Enhanced For Loop
  • Labeled For Loop
Java Simple For Loop

A for loop is a control structure that allows us to repeat certain operations by incrementing and evaluating a loop counter.

Before the first iteration, the loop counter gets initialized, then the condition evaluation is performed followed by the step definition (usually a simple incrementation).

for(initialization;condition;incr/decr) { //code to be executed }

If you observe the above syntax, In for loop there are three expressions separated by the semi-colons (;) and the execution of these expressions are as follows:

  • Initialization: Java For loop starts with the initialization statement so, initialization of counters variables is done first (For example counter = 1 or i = 1). The initialization section is executed only once at the beginning of the for loop.

  • Test Condition: The value of the counter variable is tested against the test condition. If the condition is True, compiler will execute the statements inside the For loop. If the condition fails then For loop will be terminated.

  • Increment and decrement operator: This expression is executed after the end of each iteration. This operator helps to increase or decrease the counter variable as per our requirement. Please refer Increment and decrement operators in Java article to understand the operator

Java For Loop initialization

The Java For loop has the flexibility to omit one or more sections from the declaration. Although we can skip one or more sections from the for loop but we have to put the semicolon (;) in place otherwise, it will through compilation error.

Initialize the counter variable can be skipped as shown below:

int i = 1; for( ; i <= 20; i++)

If you observe the above code snippet, the counter variable is declared before the for loop.

Like initialization, we can also skip the increment part.

int i = 1; for( ; i <= 10; ) { //statements i++; }

If you observe the above code snippet, the increment part is declared in the for loop body.

For loop allows us to initialize more than one counter variable at a time with comma separate:

for(i = 1,j = 10; i < j; i++)

For loop also allow to use multiple conditions in for loop. Instead of using comma we have to use the logical operator to separate the two condition

for(i=1,j=20; i <= 10 && j >= 20; i++) { //statements j++; }

Like the test condition, for loop allows us to use more than one increment operator as follows

for(i = 1, j = 1; i <= 10 && j <= 10; i++, j++)
Infinite For loop
for( ; ; )

NOTE: For initialization, increment and decrement operator section we can use comma to separate multiple declarations. To separate the test conditions you must use logical operator to join conditions.

for loop in java flowchart
public class ForExample { public static void main(String[] args) { System.out.println("Display n natural numbers:"); for(int i=1;i<=10;i++) { System.out.println(i); } } }

Display n natural numbers: 1 2 3 4 5 6 7 8 9 10
import java.util.Scanner; public class ForExample { public static void main(String[] args) { int n; Scanner p=new Scanner(; System.out.println("Enter any value:"); n=p.nextInt(); System.out.println("Display "+n+" natural numbers."); for(int i=1;i<=n;i++){ System.out.println(i); } } }

Enter any value: 20 Display 20 natural numbers. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Java for-each Loop

Since Java 8, we can leverage for-each loops in a slightly different way. We now have a dedicated forEach() method in the Iterable interface that accepts a lambda expression representing an action we want to perform.

It works on elements basis not index. It returns element one by one in the defined variable.

for(Type var:array){ //code to be executed }
public class ForEachExample { public static void main(String[] args) { int array[]={10,25,48,65,80}; System.out.println("Display array elements:"); for(int i:array) { System.out.println(i); } } }

Display array elements: 10 25 48 65 80
Java Labeled For Loop

We can also have labeled for loops. It’s useful if we’ve got nested for loops so that we can break/continue from aspecific for loop:

We can have name of each for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop.

labelname: for(initialization;condition;incr/decr) { //code to be executed }
public class LabeledForExample { public static void main(String[] args) { aa: for(int i=1;i<=3;i++) { bb: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break aa; } System.out.println(i+" "+j); } } } }

1 1 1 2 1 3 2 1

If you use break cc;, it will break inner loop only which is the default behavior of any loop.

public class LabeledForExampleBreak { public static void main(String[] args) { bb: for(int i=1;i<=3;i++){ cc: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break cc; } System.out.println(i+" "+j); } } } }

1 1 1 2 1 3 2 1 3 1 3 2 3 3
Java Infinitive For Loop

If you use two semicolons ;; in the for loop, it will be infinitive for loop.

for(;;){ //code to be executed }
public class ForExampleInfinitiveForLoop { public static void main(String[] args) { for(;;){ System.out.println("infinitive loop"); } } }

infinitive loop infinitive loop infinitive loop infinitive loop infinitive loop ctrl+c

Now, you need to press ctrl+c to exit from the program.