1Z0-803 · Question #127
Given: class X { static void m(StringBuilder sb1) { sb1.append("er"); } public static void main (String[] args) { StringBuilder sb2 = new StringBuilder("moth"); m(sb2); System.out.println(sb2); } } Wh
The correct answer is C. mother. The code demonstrates passing a StringBuilder object by reference to a method, which then modifies the object's content, affecting the original reference.
Question
Given:
class X { static void m(StringBuilder sb1) { sb1.append("er"); } public static void main (String[] args) { StringBuilder sb2 = new StringBuilder("moth"); m(sb2); System.out.println(sb2); } } What is the result?
Options
- Amoth
- Ber
- Cmother
- DCompilation fails
- EAn exception is thrown at run time
How the community answered
(63 responses)- A2% (1)
- B5% (3)
- C81% (51)
- D3% (2)
- E10% (6)
Why each option
The code demonstrates passing a StringBuilder object by reference to a method, which then modifies the object's content, affecting the original reference.
'moth' is incorrect because the append("er") method is called on the StringBuilder object, modifying its content.
'er' is incorrect because the StringBuilder initially contains 'moth' and 'er' is appended to it, not replacing it.
When m(sb2) is called, the sb2 reference is passed by value to sb1 in method m. Both sb1 and sb2 now refer to the same StringBuilder object. The sb1.append("er") call modifies the content of this shared StringBuilder object from "moth" to "mother" in place. System.out.println(sb2) then prints the modified content.
Compilation fails is incorrect as the code is syntactically valid and compiles successfully.
An exception is thrown at run time is incorrect as StringBuilder.append() is a valid operation and no conditions for runtime exceptions are met.
Concept tested: Java pass-by-value for object references, StringBuilder mutability
Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuilder.html#append(java.lang.String)
Topics
Community Discussion
No community discussion yet for this question.