nerdexam
Oracle

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 | |------|-----------|--------| |…

Working with Java Data Types

Question

Given:
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)
  • A
    15% (8)
  • B
    9% (5)
  • C
    5% (3)
  • D
    71% (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:

LineOperationResult
s = "this is it"Initial values = "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–9s = "is it"
x = s.indexOf("is")"is" appears at index 0 of "is it"x = 0
println(s+" "+x)Prints "is it" + " " + 0Output: is it 0

Why each distractor is wrong:

  • B - No exception occurs; substring(5) is within bounds (string length is 10), and indexOf safely returns -1 if not found (it returns 0 here anyway).
  • C - 10 would require indexOf to return a value beyond the string's length; impossible.
  • D - "this is" cannot result from substring, 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

#String.indexOf()#String.substring()#code tracing#index tracking

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice