JavaJava For and For-each Loops

Java For and For-each Loops

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In the Java while and do while loops programming tutorial, we learned about two of the most basic and oldest looping constructs. In today’s follow-up, we will conclude our examination of supported loop types in Java as we explore the for and for-each loops.

You can learn more about while and do while loops in our guide: Java While and Do While Loops.

Java For Loop

The Java for loop is often a better choice than a while or do while loop when you know exactly how many times you want to loop through a block of code.

The for loop syntax is considered to be somewhat more complex than that of other loop types in Java due to its use of three expressions. Here is an example of the for loop’s syntax:

for (initialExpression; testExpression; updateExpression) {
  // body of the loop
}

In this code example:

  1. The initialExpression initializes and/or declares variables and executes only once.
  2. The testExpression condition is evaluated. If the condition is true, the body of the for loop is executed.
  3. The updateExpression updates the value of initialExpression.
  4. The testExpression condition is evaluated again. The process continues until the condition is false.

Here is a short Java program example that prints a string five times:

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

    final int n = 5;
    // for loop  
    for (int i = 1; i <= n; i++) {
      System.out.println("Hello world!");
    }
  }
}

When executed, the program produces the following output:

Java For Loop

For loops can also be used to perform calculations, such as calculating the sum of natural numbers from 1 to 1000, as shown in the code example below:

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

    int sum = 0;
    final int n = 1000;

        for (int i = 1; i &= n; ++i) {
        sum += i;
    }

    System.out.println("Sum = " + sum);
  }
}

Here is the output of the above program:

For loop tutorial in Java

Read: Top Java Online Training Courses and Bundles

Beware of Infinite Loops

For loops are in no way immune to infinite looping, as it is possible to set the test expression in such a way that it never evaluates to false, resulting in the for loop running forever. Here is some example Java code that demonstrates an infinite for loop:

class InfiniteForLoopExample {
  public static void main(String[] args) {
    
    int sum = 0;
    
    for (int i = 1; i <= 10; i--) {
      System.out.println("Hello world!");
    }
  }
}

Here are the (partial) results, which have already exceeded the target of 10 lines:

Java for loop code examples

Read: Java Tools to Increase Productivity

The Java For-each Loop

Added in Java 1.5, the for-each loop is an alternative to the for loop that is better suited to iterating over arrays and collections. The Java for-each syntax is a whole lot simpler too; all it requires is a temporary holding variable and the iterable object:

for (type variableName : iterableObject) {
  // code block to be executed
}

In the following code example, a for-each loop is utilized to output all elements in an array of vehicles:

String[] cars = {"Volvo", "BMW", "Ford", "Infiniti", "Jaguar"};
for (String i : cars) {
  System.out.println(i);
}

As you can see in the output below, each array element is accessed in order from first to last:

Java For-each loop tutorial

Developers can also use the for-each loop to traverse through objects that store a collection such as a Map, although since Java 8 the forEach() method is considered to be a better choice:

import java.util.*;

class ForEachMapExample {
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(2, "is");
    map.put(3, "fun!");
    
    for (String word : map.values()) {
      System.out.println("Word: " + word);
    }
  }
}

In order to be able to read the map’s values, we need to first extract them from the map. To do that, we can employ the values() method; it returns a Collection of the values contained in the map.

Java for-each loop how to

Java continue and break in For and For-each Loops

Both for and for-each loops support the continue and break statements in Java. Hence, if you want to skip the current iteration, use continue:

for(int i = 0; i < 5; i++){
  if (i == 2){
     continue;
  }
}

Need to break out of the whole loop? Use break:

for(int i = 0; i < 5; i++){
  if (i == 2){
     break;
  }
}

To break out of more than one loop use break with a label:

outerLoop: // Label the loop
for(int j = 0; j < 5; j++){
  for(int i = 0; i < 5; i++){
    if (i==2){
      break outerLoop;
    }
  }
}

A word to the wise: if you find yourself checking for a lot of specific values, it might be better to either prefilter your collection or use a separate loop for each group of values.

Final Thoughts on Java For and For-each Loops

In this Java programming tutorial, we explored the very important for and for-each Java loop types. The for loop is the perfect choice when you know exactly how many times you want to loop through a block of code, while the for-each loop is ideal for iterating over the elements of a simple array. Objects that store collections such as the ArrayList and HashMap provide the forEach() instance method for the looping purposes. We also discussed the use of break and continue in for and for-each loops.

Read: Java Switch Statements

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories