nerdexam
Oracle

1Z0-803 · Question #82

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

The correct answer is C. sb.delete(0, sb.length());. To empty a StringBuilder variable in Java, you must use the delete method, specifying a range from the beginning to the current length of the buffer.

Working with Selected Classes from the Java API

Question

Which statement will emoty 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

(49 responses)
  • A
    2% (1)
  • B
    8% (4)
  • C
    86% (42)
  • D
    4% (2)

Why each option

To empty a `StringBuilder` variable in Java, you must use the `delete` method, specifying a range from the beginning to the current length of the buffer.

Asb.deleteAll();

The `StringBuilder` class does not have a method named `deleteAll()` for emptying its contents.

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

The `StringBuilder` class does not have a `size()` method; it uses `length()` to get the number of characters.

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

The `delete(int start, int end)` method of `StringBuilder` removes characters within the specified range. By setting the `start` index to 0 and the `end` index to `sb.length()`, all characters from the beginning to the end of the `StringBuilder` are effectively removed, leaving it empty.

Dsb.removeAll();

The `StringBuilder` class does not have a method named `removeAll()` for emptying its contents.

Concept tested: StringBuilder clear method, Java String methods

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

Topics

#StringBuilder#string manipulation#Java API methods

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice