Java for loop with examples

For loop is a construct used to execute a statement or block of statements ,referred to as the body of the loop, a given number of times when a certain condition remains true and stops the execution when the condition evaluates to false.

Basic syntax and its explanation

 

for(initializationVariable(s);conditionExpression;iterationExpression){

//loop body

}

//other statements

 

The variable delaration,conditional expression and iterationExpression sections must be separated by semicolons(;).

Variable(s) declaration and initialization and their scope-

This section declares one or more variables of the SAME TYPE.

If more than one variables are declared, they are comma separated.

The variables are local to the for loop and are invisible outside the loop unless they are declared outside the loop whereby, they can be used both inside and outside the loop.

The variables declaration only happens once.

  for (int a = 0; a < 10; a++) {

        }

//valid

        for (int i = 0, j = 2, k = 9; i < j; i++) {

        }

//valid multiple variables declaration

int k = 6;

        int l = 20;

 

        for (; k < l;) {

        }

//valid though will result in an endless loop since the boolean evaluation expression always returns true

 

  for (int a = 0; a < 10; a++) {

             

        } System.out.println(a);

//illegal as a is not accessible outside the loop

 

for (int i = 0, j = 2, k = 9,double m=2.5; i < j; i++) {

        }

//illegal as all variables in the variables declarations part must be of same type,again the variable type declaration is done only once.

for (int i = 0, j = 2, k = 9,int m=9; i < j; i++) {

        }

//illegal as with multiple variables declaration, the type declaration is only done once

Conditional expression(boolean)

This is the section that determines if the iterations of the loop body will execute or not.

Only one condition expression is required.Incase multiple evaluations/complex evaluations of various variables need to be evaluated,they should be structured as one expression which will eventually result in a boolean.

Example

for (int i = 0, j = 2, k = 9; i < j && k > 3; i++) {

        }

The above is a valid conditional expression since the evaluation  i < j && k > 3 will result into a boolean.

The loop expression

This is code that executes after every loop iteration.Mostly loop iteration counters are incremented or decremented . Any other code can be executed.There can be more than one loop expressions.

Let us see below examples.

      for (int a = 0; a < 10; a++) {

              System.out.println(a);

        }

In the above code block,a++ is our loop expression which increments our counter variable a.

 

There can be multiple loop expressions separated by commas like below.

       for (int a = 0; a < 10; a++,System.out.println("end of iteration")) {

              System.out.println(a);

        }

The output of the above is as below

 

Loop body

This is the block of statements or a statement of code to be executed in the loop

 

One liner  for loop body

Just like the if-else construct,for loop can also have a one liner body.

In this case,only the line immediately after the for(…) will be executed.Any line below that will be executed at the end of the loop.Example below

     for (int a = 0; a < 5; a++, System.out.println("iteration- " + a))

        System.out.println(a);       

        System.out.println("After loop");

The output of executing a program with the above for loop is

Forced exits for a loop

In the execution of a for…loop ,a forced exit can occur resulting in return of control out of the for loop.

This can be due to the following scenarios:

1.break-this jumps execution to the first statement outside the for loop.

2.return-return the execution immediately to the method that invoked the current method.

3.System.exit()-the program execution stop and the VM shuts down.

4.Exception thrown-when executing the loop body,an exception that is not handled in the loop body block will cause the flow to jump outside the for loop.

 

Endless loop without the three(3)sections

Without the variable declaration/initialization,the booolean expression and loop expression sections,the loop becomes an endless loop.

      for( ; ; ) {

         System.out.println("Endless loop");

       }

Break

Break keyword is used to jump out of the for loop(the current for loop) to the first statement after the for loop. This mainly happens after testing some condition with an if statement and deciding to discontinue the rest of the loop iterations depending on the result of the if condition check as per the business logic requirements.

Example below:

package devsought.forloop;

 

public class ForLoopBreakExample1 {

 

    public static void main(String... args) {

        String[] countries = new String[]{"Kenya", "Japan", "US", "Netherlands", "South Africa"};

        String target = "US";

        int targetPos = -1;

        for (int i = 0; i < countries.length; i++) {

            if (target.contentEquals(countries[i])) {

                targetPos = i + 1;

                break;

            }

            System.out.println("Visited " + countries[i]);

        }

        if (targetPos != -1) {

            System.out.println("Found target at position:" + targetPos);

        } else {

            System.out.println("Target not found in array");

        }

    }

}

Running the above program gives below output:

Explanation:

We are iterating the array counties in search of a target.If we find a match,we break outside the loop and print the position at which we found our target.Otherwise ,we print the current country(array element) we just visited.

If no match is found in the array,we end up printing all the array elements .

Continue

Continue is used to jump to the next loop iteration. Mostly an if condition is evaluated at start of loop body and depending on the business logic requirements of the result, a continue is hit and execution moves to the next iteration without executing the body of the current iteration. The loop expression(s) is executed  so if counter variable increment/decrement is being done on the loop expression(s),they will be executed.

Example

package devsought.forloop;

 

public class ForLoopContinueExample1 {

 

  public static void main(String... args) {

        String[] countries = new String[]{"Kenya", "Japan", "US", "Netherlands", "South Africa"};

        String skipTarget = "US";

  

        for (int i = 0; i < countries.length; i++) {

            if (skipTarget.contentEquals(countries[i])) {              

                continue;

            }

            System.out.println("Visited " + countries[i]);

        }

      

    }

}

When the above program is run we get below output:

Explanation:

We have our skipTarget set to one of the elements in the array as we iterate through it. When encountered, we continue to the next iteration without execution of the loop body which is basically printing the visited array element for our program.

 

Labelled continue

For loops can be labelled. This is helpful in scenarios whereby  there are nested for loops and we need to specify which for loop we need to continue to.

The label of a for loop mush adhere to the rules of variable naming  and ends with a colon :

Example:

package devsought.forloop;

 

public class ForLoopLabelledContinueExample1 {

 

    public static void main(String... args) {

        outer:

        for (int i = 0; i < 5; i++) {

            System.out.println("Outer loop"+(i+1));

            inner:

            for (int j = 0; j < 5; j++) {

                System.out.println(" Inner loop");

                continue outer;

            } // end of inner loop

            //code below here will never execute

            System.out.println("Out of inner loop");

        }

        System.out.println("End");

    }

}

Output:

Explanation:

For the outer loop outer we print the String “Outer loop” and append the iteration number. We then get into the inner loop inner make the first iteration and execute the code that prints out “Inner loop”.We then continue to the outerloop. If we did not continue to the outer loop ,the inner loop would make 5 iterations for each corresponding iteration of the outerloop.Since we are exiting the inner loop,the code below the end of the inner loop is never executed,i.e. the code System.out.println("Out of inner loop");

If we comment the line  section continue outer; ,the output of the program would be as below

Labelled break

This breaks out of the labelled loop,not necessarily the inner most loop unless it’s the one labelled.

Example:

package devsought.forloop;

 

public class ForLoopLabelledBreakExample1 {

 

    public static void main(String... args) {

        outer:

        for (int i = 0; i < 5; i++) {

            System.out.println("Outer loop"+(i+1));

            inner:

            for (int j = 0; j < 5; j++) {

                System.out.println(" Inner loop");

                break outer;

            } // end of inner loop

            //code below here will never execute

            System.out.println("Never executed line of code");

        }

        System.out.println("End");

    }

}

 

Output:

Explanation:

The outer loop is entered and executed.On entering the inner loop,its executed and then we break out of the outer loop.We then execute the code immediately outside the outer loop.In essence in our above program,only the first iterations of each loops are executed only once before control moving to outside the outer loop due to the break outer; statement.

The programs in this tutorial are available on Github.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.