Bird
Raised Fist0
Javaprogramming~20 mins

Enhanced for loop in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Enhanced For Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of enhanced for loop with array
What is the output of the following Java code using an enhanced for loop?
Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println(sum);
    }
}
ACompilation error
B123
C0
D6
Attempts:
2 left
💡 Hint
Think about how the enhanced for loop adds each number to sum.
❓ Predict Output
intermediate
2:00remaining
Enhanced for loop with a list
What will be printed by this Java code using an enhanced for loop over a List?
Java
import java.util.List;
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("apple");
        fruits.add("banana");
        fruits.add("cherry");
        for (String fruit : fruits) {
            System.out.print(fruit.charAt(0));
        }
    }
}
Aapplebananacherry
Ba b c
Cabc
DCompilation error
Attempts:
2 left
💡 Hint
Look at what character is printed for each fruit.
❓ Predict Output
advanced
2:00remaining
Enhanced for loop with modification inside loop
What is the output of this Java code that tries to modify array elements inside an enhanced for loop?
Java
public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        for (int x : arr) {
            x = x * 2;
        }
        for (int x : arr) {
            System.out.print(x + " ");
        }
    }
}
A1 2 3
B2 4 6
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Does changing 'x' inside the loop change the original array?
❓ Predict Output
advanced
2:00remaining
Enhanced for loop with multidimensional array
What will this Java program print when using an enhanced for loop over a 2D array?
Java
public class Main {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2}, {3, 4}};
        int total = 0;
        for (int[] row : matrix) {
            for (int val : row) {
                total += val;
            }
        }
        System.out.println(total);
    }
}
A10
BCompilation error
C24
D0
Attempts:
2 left
💡 Hint
Add all numbers in the 2D array.
🧠 Conceptual
expert
2:00remaining
Behavior of enhanced for loop with Iterable and Iterator
Which statement about the enhanced for loop in Java is true?
AIt requires manual handling of the loop index variable.
BIt internally uses an Iterator to loop over elements of Iterable collections.
CIt allows modifying the collection elements directly during iteration.
DIt can only be used with arrays, not with collections.
Attempts:
2 left
💡 Hint
Think about how enhanced for loops work with collections like ArrayList.

Practice

(1/5)
1. What is the main purpose of the enhanced for loop in Java?
easy
A. To create infinite loops
B. To iterate over all elements in an array or collection easily
C. To declare variables with enhanced types
D. To replace if-else statements

Solution

  1. Step 1: Understand the enhanced for loop usage

    The enhanced for loop is designed to simplify iterating over arrays or collections without manual index management.
  2. Step 2: Compare options with the loop's purpose

    Only To iterate over all elements in an array or collection easily correctly describes this purpose; others describe unrelated concepts.
  3. Final Answer:

    To iterate over all elements in an array or collection easily -> Option B
  4. Quick Check:

    Enhanced for loop = easy iteration [OK]
Hint: Enhanced for loop = easy way to visit each item [OK]
Common Mistakes:
  • Thinking it declares variables
  • Confusing with infinite loops
  • Using it to replace conditional statements
2. Which of the following is the correct syntax for an enhanced for loop iterating over an integer array nums?
easy
A. foreach (int num : nums) { System.out.println(num); }
B. for int num in nums { System.out.println(num); }
C. for (int num : nums) { System.out.println(num); }
D. for (num : nums) { System.out.println(num); }

Solution

  1. Step 1: Recall Java enhanced for loop syntax

    The correct syntax uses: for (type variable : arrayOrCollection) { ... }
  2. Step 2: Check each option

    for (int num : nums) { System.out.println(num); } matches the correct syntax. Options A, B, and C use incorrect keywords or missing parentheses.
  3. Final Answer:

    for (int num : nums) { System.out.println(num); } -> Option C
  4. Quick Check:

    Correct syntax uses ':' inside parentheses [OK]
Hint: Remember: for (type var : collection) { } [OK]
Common Mistakes:
  • Using 'in' instead of ':'
  • Omitting parentheses
  • Using 'foreach' keyword in Java
3. What will be the output of the following code?
int[] numbers = {1, 2, 3};
int sum = 0;
for (int n : numbers) {
    sum += n;
}
System.out.println(sum);
medium
A. 6
B. 123
C. 0
D. Compilation error

Solution

  1. Step 1: Understand the loop operation

    The loop adds each element of the array (1, 2, 3) to the variable sum.
  2. Step 2: Calculate the sum

    sum = 0 + 1 + 2 + 3 = 6
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Sum of 1, 2, 3 = 6 [OK]
Hint: Sum all elements inside the loop [OK]
Common Mistakes:
  • Concatenating numbers instead of adding
  • Forgetting to initialize sum
  • Syntax errors in loop
4. Identify the error in the following code snippet:
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
    System.out.println(fruits);
}
medium
A. Inside the loop, it should print 'fruit' instead of 'fruits'
B. The loop variable should be 'fruits' not 'fruit'
C. The array declaration is incorrect
D. Enhanced for loop cannot be used with arrays

Solution

  1. Step 1: Analyze the loop variable and print statement

    The loop variable is 'fruit', representing each element. Printing 'fruits' prints the whole array reference each time.
  2. Step 2: Correct the print statement

    To print each fruit, use 'System.out.println(fruit);' inside the loop.
  3. Final Answer:

    Inside the loop, it should print 'fruit' instead of 'fruits' -> Option A
  4. Quick Check:

    Print loop variable, not array name [OK]
Hint: Print the loop variable, not the array name [OK]
Common Mistakes:
  • Printing the array variable inside the loop
  • Confusing loop variable with array name
  • Incorrect array declaration
5. Given a list of integers, which enhanced for loop code correctly counts how many numbers are greater than 10?
List<Integer> nums = List.of(5, 12, 7, 20, 10);
int count = 0;
// Which code correctly counts numbers > 10?
hard
A. for (Integer n : nums) { if (n >= 10) count++; }
B. for (int n : nums) { if (n >= 10) count++; }
C. for (n : nums) { if (n > 10) count++; }
D. for (int n : nums) { if (n > 10) count++; }

Solution

  1. Step 1: Understand the data and requirement

    List.of(5,12,7,20,10). Numbers greater than 10: 12,20 (count=2).
  2. Step 2: Recall enhanced for loop with List<Integer>

    Supports int n via automatic unboxing of Integer to int.
  3. Step 3: Check each option

    A: >=10 counts 12,20,10 (3) incorrect.
    B: int n >10 correct syntax, condition, count=2.
    C: Missing type for n: compile error.
    D: >=10 incorrect condition.
  4. Final Answer:

    for (int n : nums) { if (n > 10) count++; } -> Option D
  5. Quick Check:

    int n works with List<Integer> via unboxing [OK]
Hint: int n works for List<Integer> via autounboxing [OK]
Common Mistakes:
  • Using >= instead of >
  • Missing type declaration for loop variable
  • Wrong comparison operator
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard