1Z0-803 · Question #107
Given the code fragment: StringBuilder sb = new StringBuilder(); sb.append("World"); Which fragment prints Hello World?
The correct answer is A. sb.insert(0, "Hello ");. The code aims to prepend a string to an existing StringBuilder object, which initially contains 'World'.
Question
Given the code fragment:
StringBuilder sb = new StringBuilder(); sb.append("World"); Which fragment prints Hello World?
Options
- Asb.insert(0, "Hello ");
- Bsb.append(0, "Hello ");
- Csb.add(0, "Hello ");
- Dsb.set(0, "Hello ");
How the community answered
(31 responses)- A87% (27)
- B3% (1)
- C6% (2)
- D3% (1)
Why each option
The code aims to prepend a string to an existing StringBuilder object, which initially contains 'World'.
The StringBuilder's `insert(int offset, String str)` method correctly inserts the specified string at the given index (0 for the beginning), modifying the object to 'Hello World'.
StringBuilder does not have an `append(int offset, String str)` method; the `append` method typically adds content to the end.
The `add` method is not a part of the standard StringBuilder API for modifying its content.
The `set` method is not a valid operation for inserting a string into a StringBuilder; `setCharAt` replaces a single character at a specific index.
Concept tested: StringBuilder string insertion methods
Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuilder.html#insert(int,java.lang.String)
Topics
Community Discussion
No community discussion yet for this question.