Object-Oriented Programming · Question 13 · Hard

What is the output of the following Java code?

static void change(StringBuilder sb) {
    sb.append("World");
    sb = new StringBuilder("New");
}
// in main:
StringBuilder s = new StringBuilder("Hello");
change(s);
System.out.println(s);
  1. Hello
  2. New
  3. HelloWorld
  4. NewWorld
Answer and explanation

Answer: C. HelloWorld

Explanation: Java passes the object reference by value. append() changes the shared object, so it now holds "HelloWorld". Reassigning sb inside the method changes only the local copy of the reference, so s is unaffected.

Previous: What is the output of the following Java code? · Next: What is the output of the following Java code?

Practise object-oriented programming

Try a fresh set of object-oriented programming questions with an explanation after every answer, free and without signing up: Object-Oriented Programming practice. Or sit a full placement mock test.

More object-oriented programming questions

More technical & programming practice

DBMS · SQL · Operating Systems · Computer Networks · Software Engineering · Cloud & DevOps · GenAI Basics · Pseudo-code

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge