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.
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)- A2% (1)
- B8% (4)
- C86% (42)
- D4% (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.
The `StringBuilder` class does not have a method named `deleteAll()` for emptying its contents.
The `StringBuilder` class does not have a `size()` method; it uses `length()` to get the number of characters.
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.
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
Community Discussion
No community discussion yet for this question.