ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
// static methods of the main class:
static void change(StringBuilder sb) {
    sb.append("X");
    sb = new StringBuilder("Y");
    sb.append("Z");
}
// in main:
StringBuilder s = new StringBuilder("A");
change(s);
System.out.print(s);
  1. A. YZ
  2. B. AX
  3. C. AXYZ
  4. D. A

Correct answer: B. AX

Java passes the reference by value. append("X") changes the shared object, so the caller sees AX. Reassigning sb only changes the local copy of the reference; the later YZ object is lost when the method returns.

More OOP with C++ and Java questions

Exams that ask this topic