Java for Loops

Jakob Jenkov
Last update: 2024-04-18

The Java for loop repeats a set of Java operations. A for loop repeats a block of code as long as some condition is true. Here is a simple Java for loop example:

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

   System.out.println("i is: " + i);

}

This example is a standard Java for loop. Inside the parentheses () after the for keyword, are three statements separated by semicolon (;).

The first statement declares an int variable named i and assigns it the value 0. This statement is only executed once, when the for loop starts.

The second statement compares the value of the i variable to the value 10. If the value of i is less than 10, then the for loop is executed one more time. This statement is executed before each repetition of the for loop.

The third statement increments the value of i. This statement is also executed once per iteration of the for loop, after the body of the for loop is executed.

The result of the for loop shown above is that the body of the loop is executed 10 times. Once for each of the values of i that are less than 10 (0 to 9).

You don't actually need the curly braces around the for loop body. If you omit the curly braces, then only the first Java statement after the for loop statement is executed. Here is an example:

for(int i = 0; i < 10; i++)
    System.out.println("i is 1: " + i);  // executed inside  loop.
    System.out.println("second line");   // executed after   loop.

In this example, only the first System.out.println() statement is executed inside the for loop. The second System.out.println() statement is not executed until after the for loop is finished.

Forgetting the curly braces around the for loop body is a common mistake. Therefore it can be a good habit to just always put them around the for loop body.

Loop Initializer, Condition and Post Iteration Operation

As mentioned earlier, the for loop contains three statements, separated by semicolons. Here is the example from above, showing the three statements:

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

   System.out.println("I is: " + i);

}

These statements each have a different role in the execution of the for loop. These roles are:

  1. Loop initializer
  2. Loop condition
  3. Post iteration operation

I'll explain the roles in a bit more detail below.

Loop Initializer

The loop initializer statement is only executed once, before the for loop begins. The loop initializer statement is typically used to initialize variables or objects that are used by the loop condition statement. In the example above (repeated below) the loop initializer statement (marked in bold) declares an int variable and assigns it the value 0.

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

   System.out.println("i is: " + i);

}

You don't need a loop initializer statement. It is optional. Here is a for loop without a loop initializer statement:


MyLoop loop = new MyLoop(10);

for( ; loop.loopAgain() ; loop.iterationDone()) {
}

Notice how an object is used to keep the state which controls the loop. Of course this object could have been declared inside the loop initializer statement. I just moved it outside the for loop to show that it is possible.

You can also initialize multiple variables inside the loop initializer statement. Here is an example of that:

for(int i=0, n=10; i < n; i++) {

}

Notice how two variables are declared. The i variable used as iteration counter, and the n variable which is used as an iteration boundary. Notice also, how the loop condition now compares the i variable to the n variable, instead of to a constant value.

Condition

The condition statement is the second statement inside the for loop parentheses. This statement is an expression that should evaluate to either true or false. If the statement evaluates to true, the for loop is evaluated one more time. If the statement evaluates to false, the for loop is not executed anymore, and execution jumps to the first statement after the body of the for loop.

Here is an example for loop with the condition statement marked in bold:

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

}

Post Iteration Operation

The third statement in the for loop is the post iteration statement. This statement is executed after each iteration of the for loop. This statement is typically used to update the variables that control the condition statement. For instance, increment a counter variable.

Here is an example for loop with the post iteration statement marked in bold:

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

}

The post iteration statement increments the variable i. In the condition statement the variable i is compared to the value 10. If i is less than 10, the for loop is executed one more time.

The post iteration statement is optional, like the loop initializer statement. Here is an example without post iteration statement:


MyLoop loop = new MyLoop(10);

for( ; loop.loopAgain() ; )) {
}

The Java for each Loop

In Java 5 a variation of the for loop was added. This variation is called the for each loop. Here is a Java for each loop example:

String[] strings = {"one", "two", "three" };

for(String aString : strings) {
    System.out.println(aString);
}

Notice the String array. This array is used inside the for each loop. Notice how a String aString variable is declared inside the parentheses of the for loop. For each iteration of the for each loop this variable will be bound to one of the String objects from the strings array. The for each loop will repeat once for each element in the strings array.

The Java for each loop can also be used with generic collections. I have explained that in more detail in my Java Iterable tutorial, which is part of my Java Collections tutorial.

The continue Command

Java contains a continue command which can be used inside Java for (and while) loops. The continue command is placed inside the body of the for loop. When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the for loop body. The next iteration of the for loop body will proceed as any other. If that iteration also meets the continue command, that iteration too will skip to the next iteration, and so forth.

Note: When the continue command skips to the next iteration of the loop, the post-iteration action is still executed for that iteration.

Here is a simple continue example inside a for loop:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
for(int i=0; i < strings.length; i++) {
    if(! strings[i].toLowerCase().startsWith("j")) {
        continue;
    }

    wordsStartingWithJ++;
}

Notice the if statement inside the for loop. This if statement checks if each String in the strings array does not start with with the letter j. If not, then the continue command is executed, and the for loop continues to the next iteration.

If the current String in the strings array does start with the letter j, then the next Java statement after the if statement is executed, and the variable wordsStartingWithJ is incremented by 1.

The continue command also works inside for each loops. Here is a for each version of the previous example:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
for(String aString : strings) {
    if(! aString.toLowerCase().startsWith("j")) {
        continue;
    }

    wordsStartingWithJ++;
}

The for loop looks a bit different, but the logic and functionality remains the same.

The break Command

The break command is a command that works inside Java for (and while) loops. When the break command is met, the Java Virtual Machine breaks out of the for loop, even if the loop condition is still true. No more iterations of the for loop are executed once a break command is met. Here is a break command example inside a for loop:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
for(int i=0; i < strings.length; i++) {
    if(strings[i].toLowerCase().startsWith("j")) {
        wordsStartingWithJ++;
    }

    if(wordsStartingWithJ >= 3) {
        break;
    }

}

Notice the second if statement inside the for loop. This if statement checks if 3 words or more have been found which starts with the letter j. If yes, the break command is executed, and the program breaks out of the for loop.

Like with the continue command, the break command also works inside for each loops. Here is the example from before, using a for each loop instead:

String[] strings = {
    "John", "Jack", "Abraham", "Jennifer", "Ann" };

int wordsStartingWithJ = 0;
for(String aString : strings) {
    if(aString.toLowerCase().startsWith("j")) {
        wordsStartingWithJ++;
    }

    if(wordsStartingWithJ >= 3) {
        break;
    }

}

Just a little difference in the for loop, but the overall functionality remains the same.

Variable Visibility in Java for Loops

Variables declared inside the parentheses or the body of a Java for loop are only visible inside the for loop body. This is true for variables of for each loops too. Look at this Java for loop example:

for(int i=0; i<10; i++) {
    String iAsNo = String.valueOf(i);
}

The variables i and iAsNo are only visible inside the for loop body. They cannot be referenced outside the for loop body.

The same is true for the aString variable in this Java for each loop example:

String strings = {"one", "two", "three" };

for(String aString : strings) {
    System.out.println(aString);
}

Since the aString variable is declared inside the parentheses of the Java for each loop, the variable is only visible inside the for each loop.

for Loops in Other Languages

For the curious reader, here are links to tutorials about for loop instructions in all the programming languages covered here at Jenkov.com:

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next