Bird
0
0

What is wrong with the following code?

medium📝 Debug Q6 of 15
Java - Strings and String Handling
What is wrong with the following code?
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb = sb + " World";
System.out.println(sb);
AStringBuilder objects cannot be printed using System.out.println.
BThe append method is used incorrectly; it should be appendAll instead.
CYou cannot use the '+' operator to concatenate a StringBuilder and a String.
DThe StringBuilder constructor requires an initial capacity argument.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the '+' Operator Usage

    The '+' operator is not defined for StringBuilder and String concatenation.
  2. Step 2: Correct Way to Append

    Use sb.append(" World") to add text to the StringBuilder.
  3. Final Answer:

    You cannot use the '+' operator to concatenate a StringBuilder and a String. correctly identifies the misuse of the '+' operator with StringBuilder.
  4. Quick Check:

    StringBuilder requires append() for concatenation, '+' is invalid [OK]
Quick Trick: Use append(), not '+' with StringBuilder [OK]
Common Mistakes:
  • Using '+' operator to concatenate StringBuilder and String
  • Thinking appendAll() is a valid method
  • Believing StringBuilder cannot be printed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes