Definition
📌 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..
Syntax
syntax
for (init; condition; update) { }
for (type item : array) { } // for-eachExample
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 + " ");
}
}
}Output
output1 2 3 4 5
Important Points
for-eachloops are cleaner when you don't need the index.- Use a classic
forloop when you need the index or want to loop backward. break/continuework exactly as in C/C++.do-whileguarantees the loop body runs at least once.
Common Mistakes
- Trying to modify the loop variable inside a for-each loop — it doesn't affect the original array.
- Forgetting to update the loop counter in a manual
whileloop, causing an infinite loop. - Off-by-one errors with
<vs<=.
Interview Tip
🎯 Before your interview
Know when for-each isn't enough — e.g., you can't remove elements from a list safely while for-each iterating it; use an
Iterator instead.
