Contents

Loops in Java: For, for-each, While, and Do-While

Written by: David Vlijmincx

Introduction

Loops allow you to iterate over collections, repeat actions, and control the flow of our programs. In this post, we'll explore the different types of loops in Java and when to use each one.

For Loop

The for loop is available in most programming languages. It's ideal for situations where you know the exact number of iterations needed.

1
2
3
4
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

For-Each

The for-each loop, simplifies iterating over collections and arrays.

1
2
3
4
List<String> cities = Arrays.asList("New York", "London", "Paris");
for (String city : cities) {
    System.out.println(city);
}

Iterating over Maps

In addition to lists and arrays, the for-each loop can also be used to iterate over the entries of a Map. This is particularly useful when you need to access both the keys and values of the map within the loop.

1
2
3
4
5
6
7
8
9
Map<String, Double> planets = new HashMap<>();
planets.put("Mercury", 0.330);
planets.put("Venus", 4.87);
planets.put("Earth", 5.97);
planets.put("Mars", 0.642);

for (Map.Entry<String, Double> entry : planets.entrySet()) {
    System.out.println(entry.getKey() + " has a mass of " + entry.getValue() + " x 10^24 kg.");
}

In this example, we use the entrySet() method to get a set of all the map's entries, which we can then iterate over using the enhanced for loop. Each entry contains a key-value pair that we can access using the getKey() and getValue() methods.

While Loop

While loops execute their body as long as a given condition is true. They're useful when the number of iterations is unknown.

1
2
3
4
5
6
7
8
int score = 0;
int maxTries = 5;
int tries = 0;

while (tries < maxTries) {
    score += rollDice();
    tries++;
}

Do-While Loop

Do-while loops are similar to while loops, but they guarantee that the body will execute at least once, even if the condition is initially false.

1
2
3
4
int number;
do {
    number = getRandomNumber();
} while (number % 2 != 0);