java-loops
A Guide to Java Loops
1. Overview
2. Intro to Loops
In programming languages, looping is a feature which facilitates the execution of a set of instructions until the controlling Boolean-expression evaluates to false.
Java provides different types of loops to fit any programming need. Each loop has its own purpose and a suitable use case to serve.
Here are the types of loops that we can find in Java:
-
Simple for loop
-
Enhanced for-each loop
-
While loop
-
Do-While loop
3. 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 statement are optional. Here’s an example of an infinite for loop:
for ( ; ; ) {
// Infinite for loop
}
3.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);
}
}
4. 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’s 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());
}
4.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));
5. While Loop
The while loop is Java’s most fundamental loop statement. It repeats a statement or a block of statements while its controlling Boolean-expression is true.
The syntax of the while loop is:
while (Boolean-expression)
statement;
The loop’s Boolean-expression is evaluated before the first iteration of the loop – which means that if the condition is evaluated to false, the loop might not run even once.
Let’s have a look at a simple example:
int i = 0;
while (i < 5) {
System.out.println("While loop: i = " + i);
}
6. Do-While Loop
The do-while loop works just like the while loop except for the fact that the first condition evaluation happens after the first iteration of the loop:
do {
statement;
} while (Boolean-expression);
Let’s have a look at a simple example:
int i = 0;
do {
System.out.println("Do-While loop: i = " + i++);
} while (i < 5);
7. Conclusion
In this quick tutorial, we showed the different types of loops that are available in the Java programming language.
We also saw how each loop serves a particular purpose given a suitable use case. We discussed the circumstances that are suitable for a given loop implementation.
As always, examples can be found over on GitHub.