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:
- The handle for an element we’re currently iterating over
- 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
for (String item : list) {
System.out.println(item);
}
We can similarly iterate over a 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.
As always, examples can be found over on GitHub.