1Z0-819 · Question #172
Given: ``java String s = "this is it"; int x = s.indexOf("is"); s = s.substring(x+3); x = s.indexOf("is"); System.out.println(s+" "+x); `` What is the result?
The correct answer is D. this is 2. There is an error in the stated answer. Tracing through the code reveals the actual output is "is it 0", which most closely matches A (likely with "it" accidentally dropped from the choice text). Step-by-step trace: | Line | Operation | Result | |------|-----------|--------| |…
Question
String s = "this is it";
int x = s.indexOf("is");
s = s.substring(x+3);
x = s.indexOf("is");
System.out.println(s+" "+x);
What is the result?Options
- Ais 0
- Ban IndexOutOfBoundsException i thrown at runtime.
- Cis 10
- Dthis is 2
How the community answered
(55 responses)- A15% (8)
- B9% (5)
- C5% (3)
- D71% (39)
Explanation
There is an error in the stated answer. Tracing through the code reveals the actual output is "is it 0", which most closely matches A (likely with "it" accidentally dropped from the choice text).
Step-by-step trace:
| Line | Operation | Result |
|---|---|---|
s = "this is it" | Initial value | s = "this is it" |
x = s.indexOf("is") | "is" first appears at index 2 (inside "this") | x = 2 |
s = s.substring(x+3) | substring(5) → characters at indices 5–9 | s = "is it" |
x = s.indexOf("is") | "is" appears at index 0 of "is it" | x = 0 |
println(s+" "+x) | Prints "is it" + " " + 0 | Output: is it 0 |
Why each distractor is wrong:
- B - No exception occurs;
substring(5)is within bounds (string length is 10), andindexOfsafely returns-1if not found (it returns0here anyway). - C -
10would requireindexOfto return a value beyond the string's length; impossible. - D -
"this is"cannot result fromsubstring, which removes characters from the front, not the back.
Memory tip: Remember that substring(n) chops off the first n characters - it does not produce a substring of length n from the start. Confusing these two is the trap this question is testing.
Topics
Community Discussion
No community discussion yet for this question.