Select Page

For loop

It takes  the following form:

for (initialization block; termination condition; update clause ) {
   statements
}

There are of three parts in the round brackets or parentheses () of the for loop:

  • Initialization block

This executes only once. One or multiple variables can be declared and initialized, but they have to be the same type.

  • Termination condition

If the condition evaluates to true, then the iteration continues, otherwise it stops.

  • Update clause, executable statement(s)

This consists of one or more executable statement(s). They are usually used to update the variables defined in the initialization block.

Statement(s) within the for loop

There can be zero, one or more statement(s) within the curly brackets or braces {} of the for loop. It is valid to have an empty block within the for loop. A loop which does nothing.

Java For loop in a diagram

Note that the three components in the round brackets are optional! The two semi-columns ( ; ; ) have to be present between the round brackets.

The initialization block can be before and outside the for loop. An empty condition is valid and implies an infinite loop. The increment or decrement of the index in the update clause is not obliged.

A for loop example

public class ForLoopTest2 {
   public static void main(String[] args) {
       /*
        * Not the third component update clause has to be an assignment.
        * For example
        * i++, i--, ++i, i=i+2
        * Not: for example i+2
        */
       // for (int i=0; i <10; i+2) { // compilation error,
       // third component is not an assignment!
       // for (int i=0; i <10; i=i+2) { // valid
       // for (int i=0; i <10; ++i) { // valid
       for (int i = 0; i < 10; i++) { // valid, same result as with ++i
           System.out.println(i);
       }
   }
}

Some examples of the for loops. You can declare multiple initialization variables, but they have to be of the same types.

public class ForLoopTest1 {
   public static void main(String[] args) {
       /*
        * Note that all three parts of a for statement are optional.
        * - Initialization block
        * - Termination condition
        * - Update clause, executable statement(s)
        *
        * It is possible to specify the initialization part outside the for loop.
        */

       int i = 0; // this is visible in every for loop,
       // so it cannot be declared again in a for loop
       for (; i < 5; i++) { // valid
           System.out.println(i);
       }

       // also valid to put the increment or decrement within the loop
       i = 0;
       for (; i < 5;) { // valid
           System.out.println("test2: i = " + i);
           i++;
       }

       // what will be the value of 1 after the loop ?
       // if i = 9, then the condition check is true, i++ set i to 10
       // then, the third component i++ is executed and changes i to 11.
       // It will exit the loop, and i = 11 is printed!
       i = 0;
       for (i = 1; i < 10; i++) {
           i++;
           System.out.println("test3: i = " + i);
       }
       System.out.println("test3 after for loop: i = " + i);

       // No statement within the for loop
       i = 0;
       for (i = 1; i < 10; i++) {
           // valid to have an empty block
       }
       System.out.println("test: multiple variables in the initialization");
       // all the variables in the initialization block have to be the same type
       // In each part there can be multiple statements or conditions
       for (int m = 0, n = 1; n <= 3 && m <= 5; m++, n++) {
           System.out.println("m = " + m + ", n = " + n);
       }

       // Not valid to have different types in the initialization block
       // It is already a syntax error
       // for (int m = 0, long n = 1; n <= 3 && m <= 5 ; m++, n++) { // not valid
       // System.out.println("m = " + m + ", n = "+ n);
       // }

   }
}

Output

$ java ForLoopTest1
0
1
2
3
4
test2: i = 0
test2: i = 1
test2: i = 2
test2: i = 3
test2: i = 4
test3: i = 2
test3: i = 4
test3: i = 6
test3: i = 8
test3: i = 10
test3 after for loop: i = 11
test: multiple variables in the initialization
m = 0, n = 1
m = 1, n = 2
m = 2, n = 3

Enhanced for loop

It is also called the for-each loop and is introduced since Java 5.

Advantages over the regular for loop

It is mainly used for iterating through a collection or list with a short and simple syntax. It is also easy to use to iterate through non-nested or nested array.

for (int element : intArray) {
   System.out.println(element);
}

Some differences compared to the regular for loop

Note that the declaration of the looping variable MUST be declared within the enhanced for loop, while it is not the case for the regular for loop. See example below:

public class EnhancedForLoopTest1 {
   public static void main(String[] args) {
       /*
       NOTE, unlike the for loop
       the declaration of the variable element MUST be in the
       brackets of the enhanced for loop !!!!
       */
       int[] intArray = {0,1,2,3,4,5};
       //int element;
       // enhanced for loop or for each loop
       // for (element : intArray) {  // compilation error,
       // the declaration of variable element must be in the brackets !!!
       for (int element : intArray) {  // valid
               System.out.println(element);
       }
   }
}

The looping variable can also be declared as final, because it is created in each iteration! While it is not the case in the regular for loop. See example below:

public class FinalIndexElementTest {
   public static void main(String[] args) {

       int[] intArray = { 1, 2, 3, 4, 5 };
       // if the element (this is not an index of the array) is final
       // in an enhanced for loop.
       // that is fine! Because the new variable element is
       // created in each iteration!
       for (final int element : intArray) {
           System.out.println(element);
       }

       // what happened if the variable i is final
       // compilation error, you cannot assign a value to
       // a final variable i, at i++
       // for (final int i=0; i <5; i++) { // final is not valid
       for (int i = 0; i < 5; i++) {
           System.out.println(i);
       }

   }
}

Limitations

It is enhanced in the context for iterating through the elements due to the compact syntax, but it is not so powerful as the regular for loop. Because the enhanced for loop cannot do the following (without adaptation of the original enhanced for loop construction):

  • It cannot be used to initialize an array and modify its elements
  • It cannot be used to delete or remove the elements in a collection
  • It cannot be used to iterate over multiple collections or arrays in the same loop. Because you can only define one looping variable in the enhanced for loop, while you can define multiple looping variables in the regular for loop.

In general the enhanced for loop should be used to iterate over collections or arrays. Don’t use it to initialize, modify or delete them.

While loop

The loop checks the condition first before it executes the statement(s) in the loop.

public class WhileLoopTest1 {
   public static void main(String[] args) {
       int i = 0;
       while (i < 10)
           i++;
       System.out.println(i); // 10

       i = 0;
       while (i < 10) {
           ++i;
           System.out.println("test i: " + i);
       }
       //
       System.out.println(i); // 10 , still 10

   }
}

Output:

$ java WhileLoopTest1
10
test i: 1
test i: 2
test i: 3
test i: 4
test i: 5
test i: 6
test i: 7
test i: 8
test i: 9
test i: 10
10

Do-While loop

This executes at least once. The condition is evaluated at the end.

public class DoWhileTest2 {
   public static void main(String[] args) {
       // will this print at least once?
       // Yes!
       // So the while condition is evaluated after the execution of the do block
       // first.
       int i = 0;
       do {
           System.out.println("i= " + i);
           i++;
       } while (i < 0);
   }
}

Output:

$ java DoWhileTest2
i= 0

In the following example the variable i is not visible for the while condition.

public class DoWhileTest1 {
   public static void main(String[] args) {
       // will this work?
       // it will not compile, because it is not visible
       // for the while condition!!
       do {
           int i = 0;
           System.out.println("i= " + i);
           i++;
       } while (i < 10); // cannot find variable i
   }
}

Don’t forget the semicolon (;) at the end of the do-while loop

Don't forget the semicolon at the end of the do while loop in java

Break and Continue in loop

Break statement

It is used to exit the for, enhanced-for, while and do-while loops, as well as the switch statement.

public class BreakTest1 {
   public static void main(String[] args) {
       //
       loop1: for (int i = 0; i < 4; i++) {
           System.out.println("1st loop, i = " + i);

           for (int j = 0; j < 4; j++) {
               System.out.println("2nd loop, j = " + j);
               if (j > 1) {
                   break; // break only this loop
               }
           }
       }
   }
}

Output:

$ java BreakTest1
1st loop, i = 0
2nd loop, j = 0
2nd loop, j = 1
2nd loop, j = 2
1st loop, i = 1
2nd loop, j = 0
2nd loop, j = 1
2nd loop, j = 2
1st loop, i = 2
2nd loop, j = 0
2nd loop, j = 1
2nd loop, j = 2
1st loop, i = 3
2nd loop, j = 0
2nd loop, j = 1
2nd loop, j = 2

Labeled break statement

You can use a labeled break statement to exit the outer loop. An example of a break to the outer loop with label loop1.

public class BreakTest1 {
   public static void main(String[] args) {
       //
       loop1: for (int i = 0; i < 4; i++) {
           System.out.println("1st loop, i = " + i);

           for (int j = 0; j < 4; j++) {
               System.out.println("2nd loop, j = " + j);
               if (j > 1) {
                   break loop1; // break to the labeled loop
               }
           }
       }
   }
}

Output:

$ java BreakTest1
1st loop, i = 0
2nd loop, j = 0
2nd loop, j = 1
2nd loop, j = 2

Break in a Switch statement

public class SwitchTest1 {
 public static void main(String[] args) {
   // enum has to be defined in similar way as a class
   // enum Gender {FEMALE, MALE, UNISEX};
   Gender gender = Gender.MALE; // has to be initialized
   // Gender gender = xx; // compile error

   /*
    * switch works with the byte, short, char, int primitive data types and their
    * wrapper classes, enum types String
    *
    * But NOT with Boolean !!!
    *
    */
   switch (gender) {
   case FEMALE:
     System.out.println("Gender is Female.");
     break;
   default: // default can be placed everywhere, but only once !
     System.out.println("Not a predefined gender");
   case MALE:
     System.out.println("Gender is male.");
     break;
     // so, without break, the statement below will be executed as well     
   case UNISEX:
     System.out.println("Gender is Unisex.");
     break;

   }
 }
}

Output:

$ java SwitchTest1
Gender is male.

Continue statement

It is used to continue to the start of the next iteration. It cannot be used in the switch statement.

public class ContinueTest1 {
   public static void main(String[] args) {
       // continue can only use in a loop construct
       for (int i = 0; i < 10; i++) {
           if (i % 2 == 0)
               continue;
           // means that the statement after continue
           // with not be executed in the iteration
           System.out.println("i= " + i);
       }
   }
}

Output:

$ java ContinueTest1
i= 1
i= 3
i= 5
i= 7
i= 9