Bird
0
0

What will be printed by this code?

medium📝 Predict Output Q5 of 15
Java - Strings and String Handling
What will be printed by this code?
String s = "Hello";
StringBuilder sb = new StringBuilder(s);
sb.append(" World");
System.out.println(s);
System.out.println(sb);
AHello World\nHello World
BHello\nHello World
CHello\nHello
DHello World\nHello
Step-by-Step Solution
Solution:
  1. Step 1: Understand String immutability

    Variable s remains "Hello" because String is immutable and not changed.
  2. Step 2: StringBuilder appends " World"

    sb becomes "Hello World" after append.
  3. Final Answer:

    Hello Hello World -> Option B
  4. Quick Check:

    String unchanged; StringBuilder changed [OK]
Quick Trick: String unchanged; StringBuilder changes with append [OK]
Common Mistakes:
  • Assuming String changes after StringBuilder append
  • Printing variables in wrong order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes