1Z0-811 · Question #39
Given the code fragment: String digits = "0123456789"; System.out.println( digits.substring( digits.indexOf("4"), digits.indexOf("8"))).concat("89")); What is the result?
The correct answer is A. 456789. Option A (456789) is correct because digits.indexOf("4") returns 4 and digits.indexOf("8") returns 8, so substring(4, 8) yields "4567" - then .concat("89") appends "89", producing "456789". Why the distractors fail: B/C (45678): This mistakes substring as inclusive on both ends…
Question
Options
- A456789
- B45678
- C45678
- D3456789
How the community answered
(37 responses)- A78% (29)
- B14% (5)
- C5% (2)
- D3% (1)
Explanation
Option A (456789) is correct because digits.indexOf("4") returns 4 and digits.indexOf("8") returns 8, so substring(4, 8) yields "4567" - then .concat("89") appends "89", producing "456789".
Why the distractors fail:
- B/C (
45678): This mistakessubstringas inclusive on both ends - but Java'ssubstring(start, end)excludes the end index, so index 8 ('8') is never included. These also ignore the.concat("89")call entirely. - D (
3456789): This suggestsindexOf("4")returns3, which would happen if someone confused the character'4'with a zero-based offset from'1'- butindexOfreturns the actual position in the string, and'4'sits at index4.
Memory tip: Think of substring(start, end) as a fence post - you start at the first post but stop before the last one. A quick way to verify: "0123456789".substring(4, 8) spans 4 characters (8 - 4 = 4), giving "4567", not five.
Topics
Community Discussion
No community discussion yet for this question.