Bird
0
0

Identify the error in the following code snippet:

medium📝 Debug Q14 of 15
Java - Strings and String Handling

Identify the error in the following code snippet:

StringBuffer sb = new StringBuffer("Test");
sb.insert(5, "ing");
System.out.println(sb);
AIndexOutOfBoundsException because insert index is invalid
BNullPointerException because sb is not initialized
CCompilation error due to wrong method name
DNo error; output is "Testing"
Step-by-Step Solution
Solution:
  1. Step 1: Check insert index validity

    StringBuffer length is 4 ("Test"), but insert index is 5, which is out of bounds.
  2. Step 2: Understand exception thrown

    Inserting at index greater than length throws IndexOutOfBoundsException.
  3. Final Answer:

    IndexOutOfBoundsException because insert index is invalid -> Option A
  4. Quick Check:

    Invalid insert index = B [OK]
Quick Trick: Insert index must be between 0 and length inclusive [OK]
Common Mistakes:
  • Assuming insert auto-corrects index
  • Confusing insert with append
  • Expecting no error on invalid index

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes