nerdexam
Oracle

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…

Working with Selected Classes from the Java API

Question

Given the code fragment: StringBuilder sb = new StringBuilder(); sb.append("World"); Which fragment prints Hello World?

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)
  • A
    93% (27)
  • B
    3% (1)
  • C
    3% (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

#StringBuilder.insert()#StringBuilder API#String manipulation#method signatures

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice