Consider the following code segment. What is printed?
String word = "notebook";
String part = word.substring(1, 4);
int pos = word.indexOf("book");
System.out.println(part + " " + pos);
not 4ote 4ote 3ote -1substring(1, 4) yields ote, and "book" begins at index 4, so the line prints ote 4.
Explanation
Indexes start at 0, and the two-argument substring stops just before its second index, so the characters at 1, 2, and 3 are returned. indexOf reports where the first occurrence of the target begins.
- A is not correct: the returned characters begin at index
1rather than index0, so the first three charactersnotare not whatsubstring(1, 4)produces. - C is not correct: the search counts from zero, so
"book"begins at index4; index3holds the character just before it. - D is not correct:
-1is returned only when the target string is not found, and"book"does appear inside"notebook".