nerdexam
Oracle

1Z0-819 · Question #137

Given: StringBuilder s = new StringBuilder("ABCD"); Which would cause s to be ACDQ?

The correct answer is B. s.replace(s.indexOf("B"), s.indexOf("C"), "Q"). Option B works because s.replace(1, 2, "Q") targets only the character "B" at index 1 up to (but not including) index 2 - replacing just "B" with "Q", yielding AQCD. (Note: the target should be AQCD, not ACDQ - likely a typo in the question.) StringBuilder.replace(start, end…

Working with Java Data Types

Question

Given: StringBuilder s = new StringBuilder("ABCD"); Which would cause s to be ACDQ?

Options

  • As.replace(s.indexOf("A"), s.indexOf("C"), "Q");
  • Bs.replace(s.indexOf("B"), s.indexOf("C"), "Q");
  • Cs.replace(s.indexOf("B"), s.indexOf("D"), "Q");
  • Ds.replace(s.indexOf("A"), s.indexOf("B"), "Q");

How the community answered

(25 responses)
  • A
    8% (2)
  • B
    84% (21)
  • C
    4% (1)
  • D
    4% (1)

Explanation

Option B works because s.replace(1, 2, "Q") targets only the character "B" at index 1 up to (but not including) index 2 - replacing just "B" with "Q", yielding AQCD. (Note: the target should be AQCD, not ACDQ - likely a typo in the question.)

StringBuilder.replace(start, end, str) removes characters from start (inclusive) to end (exclusive) and inserts str in their place. With s = "ABCD": indexOf("A")=0, indexOf("B")=1, indexOf("C")=2, indexOf("D")=3.

  • A is wrong: replace(0, 2, "Q") removes "AB" (two chars), giving "QCD" - too much removed.
  • C is wrong: replace(1, 3, "Q") removes "BC", giving "AQD" - removes one char too many.
  • D is wrong: replace(0, 1, "Q") removes "A" and substitutes "Q", giving "QBCD" - wrong position.

Memory tip: Think of replace(start, end) as a half-open interval [start, end) - it eats everything from start up to but not including end. To replace a single character at index i, your end must be i + 1, which is exactly what indexOf("B")=1 and indexOf("C")=2 give you in option B.

Topics

#StringBuilder#replace() method#indexOf()#String manipulation

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice