For-Each Loop in Java — Java Technical Interview Questions & Answers
For-Each Loop in Java
For-Each Loop in Java
- for-each (enhanced for) walks every element without an index. Read it as “for each item in this list”. Shape: for (int x : arr) System.out.println(x);
- Use it when you only need values. If you need the position, or you must replace an item by index, use a normal for with i.
- Do not remove items from a list inside for-each without an iterator — Java can throw ConcurrentModificationException. Keep for-each simple: read and print, or copy.
- Let's take this on the board with one tiny Main class — no extra files. For-Each Loop in Java — output: 10 then 20 then 30. for-each walks the array — no index variable. Start from main, go line by line, and stop at each print. That output is the proof for For-Each Loop.
Technical Interview Tip: Say when for-each is better than index-for, and when it is not.
Code Examples for For-Each Loop in Java
Example
// For-Each Loop
public class Main {
public static void main(String[] args) {
int[] nums = {10, 20, 30};
for (int x : nums) {
System.out.println(x);
}
}
}For-Each Loop in Java — output: 10 then 20 then 30. for-each walks the array — no index variable.
How to Explain For-Each Loop in Java to an Interviewer
What is for-each?
Enhanced for Walks every element No index
When should you not use for-each?
When you need the index When replacing by position
Write the shape.
for (Type x : arr)