nerdexam
Oracle

1Z0-808 · Question #67

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

The correct answer is C. sb.delete(0, sb.length()). sb.delete(0, sb.length()) is correct because StringBuilder.delete(int start, int end) removes characters from the start index (inclusive) to the end index (exclusive), and sb.length() returns the total number of characters - so this effectively clears the entire contents…

Working With Java Data Types

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

(68 responses)
  • A
    1% (1)
  • B
    3% (2)
  • C
    90% (61)
  • D
    6% (4)

Explanation

sb.delete(0, sb.length()) is correct because StringBuilder.delete(int start, int end) removes characters from the start index (inclusive) to the end index (exclusive), and sb.length() returns the total number of characters - so this effectively clears the entire contents.

Option A (deleteAll()) and D (removeAll()) don't exist in the StringBuilder API at all; they are fabricated method names designed to trip you up. Option B (sb.size()) is also wrong because StringBuilder has no size() method - that belongs to collection classes like ArrayList; the correct method for character count is length().

Memory tip: Think of StringBuilder as a ruler - it measures itself with length(), not size(). Whenever you need to clear a StringBuilder, remember the pattern delete(0, sb.length()) - "from zero to the length."

Topics

#StringBuilder#String manipulation#delete() method#Java API

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice