String against StringBuilder as a parameter — Aptitude
String against StringBuilder as a parameter: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 105 seconds
Question
What does this Java program print?
public class Main {
static void change(String s, StringBuilder sb) {
s = s + " changed";
sb.append(" changed");
}
public static void main(String[] args) {
String s = "A";
StringBuilder sb = new StringBuilder("B");
change(s, sb);
System.out.println(s + " " + sb);
}
}Options
- A B
- A B changed
- A changed B
- A changed B changed
Show the answer and the worked solution
Correct answer: B. A B changed
Worked solution
- s = s + " changed" builds a new String and points the local parameter at it, leaving the caller's s untouched at A.
- sb.append modifies the StringBuilder object itself, and the caller holds a reference to that same object, so the change is visible.
- The program prints A B changed.
Answer: A B changed.
The idea
Mutating the object a reference points at is visible to the caller; repointing the reference is not. Because String is immutable, only the second kind of operation is ever available for it.
Shortcut. Ask which line mutates an object: append does, while s = s + … only repoints the local name, so only sb's text changes.
Common trap. "A changed B changed" treats s = s + " changed" as changing the caller's String, when it builds a new String bound only to the parameter.
All Programming Fundamentals questions · placement mock tests