1Z0-808 · Question #90
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 "); System.out.println(sb). Option A is correct because StringBuilder.insert(int offset, String str) inserts the given string at the specified index - insert(0, "Hello ") places "Hello " at position 0, shifting "World" right, producing "Hello World". Option B fails because append only adds to the end of…
Question
Options
- Asb.insert(0, "Hello "); System.out.println(sb);
- Bsb.append(0, "Hello "); System.out.println(sb);
- Csb.add(0, "Hello "); System.out.println(sb);
- Dsb.set(0, "Hello "); System.out.println(sb);
How the community answered
(29 responses)- A93% (27)
- B3% (1)
- C3% (1)
Explanation
Option A is correct because StringBuilder.insert(int offset, String str) inserts the given string at the specified index - insert(0, "Hello ") places "Hello " at position 0, shifting "World" right, producing "Hello World".
Option B fails because append only adds to the end of the buffer and takes a single argument (no index parameter), so sb.append(0, "Hello ") won't even compile. Option C is wrong because StringBuilder has no add method - that's a List method. Option D is incorrect because set doesn't exist on StringBuilder; the closest real method is setCharAt, which replaces a single character, not a substring.
Memory tip: Think of insert like inserting a page into a book - you specify where to put it. If you only need to tack something onto the end, use append; if you need to place it at a specific position, use insert(index, str).
Topics
Community Discussion
No community discussion yet for this question.