nerdexam
Oracle

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.

Working with Selected Classes from the Java API

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)
  • A
    2% (1)
  • B
    5% (3)
  • C
    81% (51)
  • D
    3% (2)
  • E
    10% (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.

Amoth

'moth' is incorrect because the append("er") method is called on the StringBuilder object, modifying its content.

Ber

'er' is incorrect because the StringBuilder initially contains 'moth' and 'er' is appended to it, not replacing it.

CmotherCorrect

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.

DCompilation fails

Compilation fails is incorrect as the code is syntactically valid and compiles successfully.

EAn exception is thrown at run time

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

#StringBuilder#method parameters#pass by value (reference)#mutability

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice