Curriculum / Java / Lesson 07

Loops in Java

Java offers the same loop types as C/C++ — for, while, do-while — plus an enhanced for-each loop for iterating over arrays and collections cleanly..

7 of 11
beginner 📖 5 min read 🎯 1 question

Loops

Java offers the same loop types as C/C++ — for, while, do-while — plus an enhanced for-each loop for iterating over arrays and collections cleanly.

💡 Key insight The for-each loop in Java is the idiomatic way to iterate over arrays and collections like ArrayList when you don't need the index.

Syntax

syntax
for (init; condition; update) { }
for (type item : array) { }  // for-each

Example

The for-each loop reads each element of nums without needing to manage an index variable.

java
public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        for (int n : nums) {
            System.out.print(n + " ");
        }
    }
}
output1 2 3 4 5

Try it yourself

Copy this example into the Java compiler and run it — try changing a value and see what happens.

Quick Quiz

1. Which loop type is best when you need the current index while iterating an array?

Back to curriculum