Bird
0
0

The following code is intended to print all elements of the array data, but it causes a runtime error. What is the error?

medium📝 Debug Q14 of 15
Java - Arrays
The following code is intended to print all elements of the array data, but it causes a runtime error. What is the error?
int[] data = {10, 20, 30};
for (int i = 1; i <= data.length; i++) {
    System.out.println(data[i]);
}
AArrayIndexOutOfBoundsException because loop goes beyond last index
BSyntax error due to wrong for loop syntax
CPrints all elements correctly
DNullPointerException because array is not initialized
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop indices and array length

    The array has length 3, valid indices are 0, 1, 2. The loop runs i from 1 to 3 inclusive.
  2. Step 2: Identify index causing error

    When i = 3, data[3] is accessed, which is out of bounds and causes ArrayIndexOutOfBoundsException.
  3. Final Answer:

    ArrayIndexOutOfBoundsException because loop goes beyond last index -> Option A
  4. Quick Check:

    Loop index must be less than length [OK]
Quick Trick: Loop indices must be 0 to length-1 for arrays [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Starting loop at 1 instead of 0
  • Ignoring zero-based indexing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes