Bird
0
0

Find the issue in this code:

medium📝 Debug Q7 of 15
Java - Wrapper Classes
Find the issue in this code:
List list = new ArrayList<>();
list.add(10);
int sum = 0;
for(Integer num : list) {
    sum += num;
}
System.out.println(sum);
ACode works and prints 10
BRuntime NullPointerException
CCompilation error due to incompatible types
DInfinite loop occurs
Step-by-Step Solution
Solution:
  1. Step 1: Check autoboxing and unboxing in loop

    Adding 10 to list autoboxes int to Integer. In the loop, num unboxes to int for addition.
  2. Step 2: Verify code correctness

    All types match, no nulls, so sum accumulates 10 and prints correctly.
  3. Final Answer:

    Code works and prints 10 -> Option A
  4. Quick Check:

    Autoboxing and unboxing work seamlessly in collections [OK]
Quick Trick: Autoboxing works smoothly with collections and loops [OK]
Common Mistakes:
  • Expecting errors when mixing primitives and wrappers in collections
  • Thinking explicit unboxing is needed
  • Assuming NullPointerException without null values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes