nerdexam
Oracle

1Z0-803 · Question #107

Given the code fragment: StringBuilder sb = new StringBuilder(); sb.append("World"); Which fragment prints Hello World?

The correct answer is A. sb.insert(0, "Hello ");. The code aims to prepend a string to an existing StringBuilder object, which initially contains 'World'.

Working with Selected Classes from the Java API

Question

Given the code fragment:

StringBuilder sb = new StringBuilder(); sb.append("World"); Which fragment prints Hello World?

Options

  • Asb.insert(0, "Hello ");
  • Bsb.append(0, "Hello ");
  • Csb.add(0, "Hello ");
  • Dsb.set(0, "Hello ");

How the community answered

(31 responses)
  • A
    87% (27)
  • B
    3% (1)
  • C
    6% (2)
  • D
    3% (1)

Why each option

The code aims to prepend a string to an existing StringBuilder object, which initially contains 'World'.

Asb.insert(0, "Hello ");Correct

The StringBuilder's `insert(int offset, String str)` method correctly inserts the specified string at the given index (0 for the beginning), modifying the object to 'Hello World'.

Bsb.append(0, "Hello ");

StringBuilder does not have an `append(int offset, String str)` method; the `append` method typically adds content to the end.

Csb.add(0, "Hello ");

The `add` method is not a part of the standard StringBuilder API for modifying its content.

Dsb.set(0, "Hello ");

The `set` method is not a valid operation for inserting a string into a StringBuilder; `setCharAt` replaces a single character at a specific index.

Concept tested: StringBuilder string insertion methods

Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuilder.html#insert(int,java.lang.String)

Topics

#StringBuilder#String manipulation#API methods

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice