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.
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)- A4% (1)
- B4% (1)
- C85% (22)
- D8% (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.
The `StringBuilder` class does not have a method named `deleteAll`.
The `StringBuilder` class uses the `length()` method to get its current length, not `size()`.
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.
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
Community Discussion
No community discussion yet for this question.