Bird
0
0

Find the error in this Java code snippet:

medium📝 Debug Q7 of 15
Java - Arrays

Find the error in this Java code snippet:

int[] arr;
arr[0] = 5;
ASyntax error: missing array size in declaration
Barr is declared but not initialized, causes NullPointerException
CArrayIndexOutOfBoundsException because array is empty
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check array declaration and initialization

    arr is declared but not initialized with new, so it points to null.
  2. Step 2: Analyze assignment to arr[0]

    Assigning to arr[0] causes NullPointerException because arr is null.
  3. Final Answer:

    arr is declared but not initialized, causes NullPointerException -> Option B
  4. Quick Check:

    Arrays must be initialized before use [OK]
Quick Trick: Always initialize arrays before accessing elements [OK]
Common Mistakes:
  • Assuming declaration allocates memory
  • Confusing NullPointerException with syntax errors
  • Trying to assign before initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes