Java course menu
Java for Loops in Depth: Counting, for-each, Nested Loops and Patterns
Go deeper with Java for loops: counting up and down, custom steps, multiple loop variables, the enhanced for-each loop and its limits, looping over a Map, nested loops and star patterns, and the classic sum, max and count patterns.
On this page
The Loops lesson introduced the for loop. This lesson covers the variations you will write every day, and the classic patterns that appear in exercises and interviews.
Counting in different ways#
public class Main {
public static void main(String[] args) {
for (int i = 10; i > 0; i -= 3) { // count down in steps of 3
System.out.print(i + " ");
}
System.out.println();
for (int i = 1; i <= 100; i *= 2) { // powers of two
System.out.print(i + " ");
}
System.out.println();
}
}10 7 4 1
1 2 4 8 16 32 64 Several loop variables#
Separate several variables with commas. Walking from both ends towards the middle is a common use:
public class Main {
public static void main(String[] args) {
String word = "level";
boolean palindrome = true;
for (int left = 0, right = word.length() - 1; left < right; left++, right--) {
if (word.charAt(left) != word.charAt(right)) {
palindrome = false;
}
}
System.out.println(word + (palindrome ? " is" : " is not") + " a palindrome");
}
}level is a palindromeThe enhanced for loop in detail#
The for-each loop gives you each element, not its position:
public class Main {
public static void main(String[] args) {
int[] prices = {120, 45, 300};
int total = 0;
for (int p : prices) {
total += p;
}
System.out.println("Total: " + total);
for (int p : prices) {
p += 10; // changes only the loop variable!
}
System.out.println(prices[0]);
for (int i = 0; i < prices.length; i++) {
prices[i] += 10; // changes the array
}
System.out.println(prices[0]);
}
}Total: 465
120
130The loop variable is a copy of each element (for primitives) or of each reference (for objects). Assigning to it does not change the array or collection. Use an index loop when you need to replace elements or know the position.
Looping over a Map#
A Map has no single "element", so loop over its entrySet(), which gives key-value pairs:
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of("pens", 40, "books", 12, "bags", 5));
for (Map.Entry<String, Integer> entry : stock.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
stock.forEach((item, count) -> System.out.println(item + " -> " + count));
}
}bags: 5
books: 12
pens: 40
bags -> 5
books -> 12
pens -> 40A TreeMap keeps its keys sorted; see HashMap and TreeMap. The forEach with an arrow is a lambda, covered in Lambdas.
Nested loops#
A loop inside a loop runs the inner loop completely for each step of the outer one:
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print(row * col + "\t");
}
System.out.println();
}
}
}1 2 3 4
2 4 6 8
3 6 9 12 Printing patterns#
public class Main {
public static void main(String[] args) {
int height = 4;
for (int row = 1; row <= height; row++) {
System.out.println(" ".repeat(height - row) + "*".repeat(2 * row - 1));
}
}
} *
***
*****
*******String.repeat(n) (Java 11) repeats a string n times, which removes the need for two inner loops.
The core loop patterns#
public class Main {
public static void main(String[] args) {
int[] values = {14, 3, 27, 8, 19};
int sum = 0;
int largest = values[0];
int evenCount = 0;
for (int v : values) {
sum += v;
if (v > largest) largest = v;
if (v % 2 == 0) evenCount++;
}
System.out.println("Sum: " + sum);
System.out.println("Largest: " + largest);
System.out.println("Even numbers: " + evenCount);
}
}Sum: 71
Largest: 27
Even numbers: 2Accumulate, track the best so far, and count matches: these three patterns solve most loop problems. Streams can express them in one line, such as Arrays.stream(values).sum().
Common mistakes#
Practice#
Practice exercise
Print this right-angled number triangle using nested loops:
1
1 2
1 2 3
1 2 3 4Show solution
public class Triangle {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
StringBuilder line = new StringBuilder();
for (int n = 1; n <= row; n++) {
if (n > 1) line.append(' ');
line.append(n);
}
System.out.println(line);
}
}
}1
1 2
1 2 3
1 2 3 4StringBuilder builds the line efficiently; see StringBuilder.
Practice exercise
Given int[] marks = {56, 91, 78, 34, 88};, print the average as a decimal and how many marks are 75 or above.
Show solution
public class Marks {
public static void main(String[] args) {
int[] marks = {56, 91, 78, 34, 88};
int total = 0;
int high = 0;
for (int m : marks) {
total += m;
if (m >= 75) high++;
}
System.out.println("Average: " + (double) total / marks.length);
System.out.println("75 or above: " + high);
}
}Average: 69.4
75 or above: 3Key takeaway#
Finished this lesson?