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-eachExample
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.
