Recall & Review
beginner
What is an enhanced for loop in Java?
An enhanced for loop is a simpler way to iterate over arrays or collections without using an index variable. It automatically goes through each element one by one.
Click to reveal answer
beginner
Syntax of an enhanced for loop in Java?
for (Type variable : collection) {
// code using variable
}
Click to reveal answer
intermediate
Can you modify the elements of an array using an enhanced for loop?
No, the enhanced for loop provides a copy of each element, so modifying the loop variable does not change the original array elements.
Click to reveal answer
beginner
What types of data structures can you use with an enhanced for loop?
You can use arrays and any class that implements the Iterable interface, like ArrayList, LinkedList, HashSet, etc.Click to reveal answer
beginner
Example: How to print all elements of an int array using enhanced for loop?
int[] numbers = {1, 2, 3};
for (int num : numbers) {
System.out.println(num);
}
Click to reveal answer
What does the enhanced for loop automatically handle?
✗ Incorrect
The enhanced for loop automatically handles indexing through elements, so you don't need to manage the index manually.
Which of these can NOT be used directly in an enhanced for loop?
✗ Incorrect
HashMap does not implement Iterable directly, so you cannot use it directly in an enhanced for loop without calling keySet(), values(), or entrySet().
What happens if you try to modify the loop variable inside an enhanced for loop?
✗ Incorrect
The loop variable is a copy of each element, so modifying it does not affect the original array or collection elements.
Which keyword is used in the enhanced for loop syntax?
✗ Incorrect
The colon ':' is used in the enhanced for loop syntax to separate the variable and the collection.
What is the main advantage of using an enhanced for loop?
✗ Incorrect
The enhanced for loop makes code simpler and less error-prone by removing the need to manage indexes manually.
Explain how an enhanced for loop works and when you would use it.
Think about how it replaces the traditional for loop with index.
You got /4 concepts.
Write a simple Java code snippet using an enhanced for loop to print all elements of a String array.
Use for (String item : array) and System.out.println inside the loop.
You got /3 concepts.