Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this article, we’ll look at a core aspect of the Java language – executing a statement or a group of statements repeatedly using a for loop.

2. Simple for Loop

A for loop is a control structure that allows us to repeat certain operations by incrementing and evaluating a loop counter.

Before the first iteration, the loop counter gets initialized, then the condition evaluation is performed followed by the step definition (usually a simple incrementation).

The syntax of the for loop is:

for (initialization; Boolean-expression; step) 
  statement;

Let’s see it in a simple example:

for (int i = 0; i < 5; i++) {
    System.out.println("Simple for loop: i = " + i);
}

The initialization, Boolean-expression, and step used in for statements are optional. Here’s an example of an infinite for loop:

for ( ; ; ) {
    // Infinite for loop
}

2.1. Labeled for Loops

We can also have labeled for loops. It’s useful if we’ve got nested for loops so that we can break/continue from aspecific for loop:

aa: for (int i = 1; i <= 3; i++) {
    if (i == 1)
      continue;
    bb: for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break aa;
        }
        System.out.println(i + " " + j);
    }
}

3. Enhanced for Loop

Since Java 5, we have a second kind of for loop called the enhanced for which makes it easier to iterate over all elements in an array or a collection.

The syntax of the enhanced for loop is:

for(Type item : items)
  statement;

Since this loop is simplified in comparison to the standard for loop, we need to declare only two things when initializing a loop:

  1. The handle for an element we’re currently iterating over
  2. The source array/collection we’re iterating

Therefore, we can say that: For each element in items, assign the element to the item variable and run the body of the loop.

Let’s have a look at the simple example:

int[] intArr = { 0,1,2,3,4 }; 
for (int num : intArr) {
    System.out.println("Enhanced for-each loop: i = " + num);
}

We can use it to iterate over various Java data structures:

Given a List<String> list object – we can iterate it:

for (String item : list) {
    System.out.println(item);
}

We can similarly iterate over a Set<String> set:

for (String item : set) {
    System.out.println(item);
}

And, given a Map<String,Integer> map we can iterate over it as well:

for (Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(
      "Key: " + entry.getKey() + 
      " - " + 
      "Value: " + entry.getValue());
}

3.1. Iterable.forEach()

Since Java 8, we can leverage for-each loops in a slightly different way. We now have a dedicated forEach() method in the Iterable interface that accepts a lambda expression representing an action we want to perform.

Internally, it simply delegates the job to the standard loop:

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

Let’s have a look at the example:

List<String> names = new ArrayList<>();
names.add("Larry");
names.add("Steve");
names.add("James");
names.add("Conan");
names.add("Ellen");

names.forEach(name -> System.out.println(name));

4. Conclusion

In this quick tutorial, we explored Java’s for loop.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW