nerdexam
Oracle

1Z0-803 · Question #104

Which statement will empty the contents of a StringBuilder variable named sb?

The correct answer is C. sb.delete(0, sb.length());. To clear a StringBuilder variable, use its delete method with a start index of 0 and an end index equal to its current length, effectively removing all characters.

Working with Selected Classes from the Java API

Question

Which statement will empty the contents of a StringBuilder variable named sb?

Options

  • Asb.deleteAll;
  • Bsb.delete(0, sb.size());
  • Csb.delete(0, sb.length());
  • Dsb.removeAll();

How the community answered

(26 responses)
  • A
    4% (1)
  • B
    4% (1)
  • C
    85% (22)
  • D
    8% (2)

Why each option

To clear a `StringBuilder` variable, use its `delete` method with a start index of 0 and an end index equal to its current length, effectively removing all characters.

Asb.deleteAll;

The `StringBuilder` class does not have a method named `deleteAll`.

Bsb.delete(0, sb.size());

The `StringBuilder` class uses the `length()` method to get its current length, not `size()`.

Csb.delete(0, sb.length());Correct

The `StringBuilder.delete(int start, int end)` method removes the characters in a substring of this sequence. Passing `0` as the start index and `sb.length()` as the end index will delete all characters, making the `StringBuilder` empty.

Dsb.removeAll();

The `StringBuilder` class does not have a method named `removeAll`.

Concept tested: StringBuilder manipulation methods

Source: https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html#delete-int-int-

Topics

#StringBuilder#String manipulation#API methods

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice