Bird
0
0

Identify the error in this array traversal code:

medium📝 Debug Q14 of 15
Java - Arrays
Identify the error in this array traversal code:
int[] data = {2, 4, 6};
for(int i = 0; i <= data.length; i++) {
  System.out.println(data[i]);
}
ASystem.out.println should be outside the loop
BArray declaration is incorrect
CLoop condition should be i < data.length, not <= data.length
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop condition

    The loop runs while i <= data.length, which means i can be equal to data.length (3).
  2. Step 2: Check array index access

    Accessing data[3] causes ArrayIndexOutOfBoundsException because valid indices are 0 to 2.
  3. Final Answer:

    Loop condition should be i < data.length, not <= data.length -> Option C
  4. Quick Check:

    Index must be less than length to avoid error [OK]
Quick Trick: Use i < length, not i <= length in loops [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Ignoring array index limits
  • Thinking loop runs without error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes