Java for Loops: Explained With Examples
Repetition, alongside decision-making and code reuse, is one of the core building blocks of programming. Like other C-family languages, Java has supported the traditional for loop since version 1. Java later introduced the enhanced for loop, often called the for-each loop, which remains a standard way to iterate over arrays and collections in modern versions of Java.
Repetition, alongside decision-making and code reuse, is one of the core building blocks of programming. Like other C-family languages, Java has supported the traditional for loop since version 1. Java later introduced the enhanced for loop, often called the for-each loop, which remains a standard way to iterate over arrays and collections in modern versions of Java.

Diogo Kollross
Diogo Kollross is a Full-stack Engineer with more than 14 years of professional experience using many different tech stacks. He has liked programming since he was a child, and enjoys good food and traveling.
Repetition, alongside decision-making and code reuse, is one of the core building blocks of programming. Like other C-family languages, Java has supported the traditional ‘for’ loop since version 1. Java later introduced the enhanced ‘for’ loop, often called the ‘for-each’ loop, which remains a standard way to iterate over arrays and collections in modern versions of Java.
Table of contents
Basic for Statement
This is the basic for loop found in C-family programming languages. It is also known as a numeric loop.
It has three optional parts, separated by semicolons: initialization, condition, and advancement. All three parts are optional, but in most cases, you will use all three.
for (<initialization>; <condition>; <advancement>) {
//
}
The first part, initialization, sets up the control variable that determines when the loop should end. Since this variable is usually only needed inside the loop, it is commonly declared in the initialization part of the for loop.
for (int i = 0; <condition>; <advancement>) {
//
}
The next part, condition, determines whether the loop should continue. In Java, this must be an expression that returns a Boolean value. When the loop is used as a counter, which is common, the condition usually compares the control variable with an upper limit. However, this is not required and depends on the algorithm you are writing.
for (int i = 0; i < 5; <advancement>) {
//
}
Finally, the advancement part updates the control variable for the next iteration. When counting, this usually means incrementing the control variable.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
/*
0
1
2
3
4
*/
The code above will print numbers from 0 to 4, which is useful for iterating over a five-item array, as shown in the example below.
int[] myArray = new int[] { 10, 15, 20, 31, 25 };
for (int i = 0; i < 5; i++) {
int element = myArray[i];
System.out.println(element);
}
/*
10
15
20
31
25
*/
Most of the time, you’ll iterate from 0 to n - 1, where n is the size of the collection, because Java arrays and many Java collections use zero-based indexing. If you need to count from 1 to n, replace < with <= in the condition.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
/*
1
2
3
4
5
*/
Enhanced for Statement
Since Java 5, Java has supported the enhanced for statement, also known as the for-each loop. This form of for loop lets you iterate over arrays and collections without calculating each element’s index or explicitly advancing an iterator.
The enhanced for statement has this format:
for (<loop variable> : <iterable>) {
//
}
The loop variable declares a variable that takes on the value of each element during the iteration. The iterable part can be an array or an object whose class implements the Iterable interface. Common examples include Collection, List, ArrayList, and Set.
The previous example that prints all elements of an array can be written like this:
int[] myArray = new int[] { 10, 15, 20, 31, 25 };
for (int element : myArray) {
System.out.println(element);
}
/*
10
15
20
31
25
*/
Notice that you do not need to calculate each element’s index or write a separate line to retrieve the indexed element from the array. Since the enhanced for loop is shorter and more readable, it is preferable in most use cases.
Break and Continue
Break
Sometimes, you may need to break out of a loop. In other words, you stop iterating and jump to the first statement after the for loop body. One common use of the break statement is when searching for an element:
List<String> colorList = Arrays.asList("Cyan", "AliceBlue",
"Violet", "Gold");
String startingWithA = null;
for (String color : colorList) {
if (color.charAt(0) == 'A') {
startingWithA = color;
break;
}
}
System.out.println(startingWithA);
/*
AliceBlue
*/
The code above finds the first element that starts with A. If no element starts with that letter, the variable startingWithA remains unchanged with a value of null.
Some algorithms require nested loops, where you may need to break out of the outer loop from inside the inner loop. One option is to extract that logic into a separate function and use a return statement to exit the function.
private String selectColor(char[] interestingLetters,
Iterable<String> colorList) {
for (char interestingLetter : interestingLetters) {
for (String color : colorList) {
if (color.charAt(0) == interestingLetter) {
return color;
}
}
}
return null;
}
private void printSelectedColor() {
char[] interestingLetters = new char[] { 'X', 'V' };
List<String> colorList = Arrays.asList("Cyan", "AliceBlue",
"Violet", "Gold");
String selectedColor = selectColor(interestingLetters, colorList);
System.out.println(selectedColor);
}
/*
Violet
*/
The code above uses that strategy. The selectColor function finds the first color that starts with any of the letters passed in the first parameter. Because the code needs to exit all loops simultaneously, it uses the return statement inside selectColor.
The return statement cannot be placed inside printSelectedColor, because that would exit the function too early and prevent the following println call from running.
Continue
The continue statement skips the rest of the current for loop body and moves to the next iteration. It is useful when you want to avoid deeply nested if statements and keep the loop easier to read.
The following example creates a list of color names that start with G and have up to five characters:
List<String> colorList = Arrays.asList("Green", "AliceBlue",
"Violet", "GreenYellow");
List<String> shortStartingWithG = new ArrayList<>();
for (String color : colorList) {
if (color.charAt(0) == 'G') {
if (color.length() <= 5) {
shortStartingWithG.add(color);
}
}
}
System.out.println(shortStartingWithG);
/*
[Green]
*/
This works, but it requires excessive indentation inside the for loop body, which can make the code harder to read. One way to simplify the structure is to use the continue statement, as shown below.
List<String> colorList = Arrays.asList("Green", "AliceBlue",
"Violet", "GreenYellow");
List<String> shortStartingWithG = new ArrayList<>();
for (String color : colorList) {
if (color.charAt(0) != 'G') {
continue;
}
if (color.length() > 5) {
continue;
}
shortStartingWithG.add(color);
}
System.out.println(shortStartingWithG);
/*
[Green]
*/
Advanced Use Cases
for-each with index
Sometimes you may want to use a for-each loop while still tracking the index of each element. In those cases, you can calculate the index explicitly. Initialize the counter immediately before the loop, then increment it before the loop body closes:
List<String> colorList = Arrays.asList("Cyan", "AliceBlue",
"Violet", "Gold");
int i = 1;
for (String color : colorList) {
System.out.println(i + " - " + color);
i++;
}
/*
1 - Cyan
2 - AliceBlue
3 - Violet
4 - Gold
*/
Iterator Interface
The enhanced for statement works out of the box with the modern Iterable interface, but a few JDK classes still rely on older iteration patterns. One example is the Iterator interface, which is used by classes such as Scanner.
The Scanner class can parse space-separated words and primitive values, such as integers or floats, from a string. You can use a basic for loop to iterate through its results.
String input = "10 15 20 35";
for (Scanner scanner = new Scanner(input); scanner.hasNextInt();) {
int number = scanner.nextInt();
System.out.println(number);
}
/*
10
15
20
35
*/
As you can see, the advancement part of the loop is unused because it is not needed in this case. Arguably, an iterator is best iterated using the while statement as it`s slightly more readable:
String input = "10 15 20 35";
Scanner scanner = new Scanner(input);
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println(number);
}
/*
10
15
20
35
*/
Enumeration
Another older interface is Enumeration. This interface is used to list the files inside a ZIP file when using the ZipFile class. Again, we can iterate over its entries with a basic for loop:
ZipFile file = new ZipFile("example.zip");
for (Enumeration<? extends ZipEntry> entries = file.entries();
entries.hasMoreElements();) {
ZipEntry entry = entries.nextElement();
System.out.println(entry.getName());
}
As in the Iterator example, this loop does not use the third part of the for statement. You could also write it with a while statement:
ZipFile file = new ZipFile("example.zip");
Enumeration<? extends ZipEntry> entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
System.out.println(entry.getName());
}
Conclusion
To summarize, Java offers several ways to iterate over different types of sequences.
In most cases, the for-each loop is the most readable option when working with arrays, lists, and similar collections, even when you need to track an index alongside each element.
Common exceptions include using the basic for loop when you need a sequence of numbers, and using a while loop to iterate over objects that use the Iterator or Enumeration interfaces.
FAQs
Q: What are the three types of Java loops?
The three main types of Java loops are:
-
forloop: Iterates a specific number of times or over a sequence. -
whileloop: Continues as long as a condition is true. -
do-whileloop: Executes at least once, then continues if a condition is true.
Q: How do Java loops work?
Java loops repeatedly execute a block of code based on a specified condition. The for loop initializes, checks a condition, and updates in each iteration. The while loop checks a condition before each iteration. The do-while loop runs at least once, checking the condition after each iteration.
