Enhanced for-each — Concept Check
Questions on Enhanced for-each. The cleanest loop syntax in Java — works on arrays and any Iterable with no index boilerplate, and how it compares to classic for and Iterator.
Questions in this quiz
8 questions on Enhanced for-each — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have an array of integers and you want to sum all elements. Which loop style is most concise and appropriate?
- AEnhanced for-each loop
- BClassic for loop with index
- CWhile loop with iterator
- DDo-while loop
2.A developer tries to remove elements from a list using a for-each loop but encounters an error. Why?
- AList does not support removal
- Bfor-each does not support element removal
- CArrayList does not support removal
- DIterator does not support removal
3.What happens when you use an enhanced for-each loop on a 2D array in Java?
- ARequires an explicit iterator
- BIterates over each sub-array
- CIterates over each element directly
- DThrows a compilation error
4.A developer needs to iterate over two lists in sync. Which loop should they use?
- AWhile loop with iterator
- BforEach method with lambda
- CClassic for loop
- DEnhanced for-each loop
5.When should you avoid using an enhanced for-each loop?
- AWhen you need to modify elements in-place
- BWhen calculating a sum
- CWhen printing elements
- DWhen iterating over an array
6.A developer uses forEach method with a lambda expression on a list. What is a limitation they face?
- ACannot print elements
- BCannot modify elements
- CCannot use break or continue
- DCannot iterate over arrays
7.What is the main advantage of using the enhanced for-each loop over the classic for loop?
- AAllows element removal
- BSimplifies iteration without needing index
- CSupports bi-directional traversal
- DEnables skipping elements
8.A developer mistakenly believes the enhanced for-each loop can iterate in reverse. What is the correct approach?
- AUse a classic for loop with decrementing index
- BUse an enhanced for-each loop
- CUse a while loop with iterator
- DUse a forEach method with lambda