Question 381
What is printed?
String s = "COMPUTATION";
String a = s.substring(0, 3);
String b = s.substring(s.length() - 3);
String c = a + b;
System.out.println(c.indexOf("IO") + c.length());Main Solution
Step-by-step trace:
s = "COMPUTATION"(length = 11)a = s.substring(0, 3)→ characters at indices 0, 1, 2 →"COM"b = s.substring(s.length() - 3)=s.substring(8)→ characters at indices 8, 9, 10 →"ION"c = a + b="COM" + "ION"="COMION"c.indexOf("IO"): search for"IO"in"COMION". The substring"IO"starts at index 3. Soc.indexOf("IO") = 3.c.length()= 6c.indexOf("IO") + c.length()=3 + 6= 9
The answer is A) 9.
Teacher Explanation
substring(0,3) extracts indices 0–2 ("COM"); substring(8) extracts indices 8–10 ("ION"). Concatenated: "COMION" (length 6). indexOf("IO") returns 3 (0-based). 3 + 6 = 9.
Education Coach Advice
Always trace substring calls carefully: substring(start, end) is exclusive of end, and substring(start) goes to the end of the string. Then re-index the new concatenated string from 0 when using indexOf. Write out the resulting string character by character to avoid off-by-one errors.
Traps
Common traps:
- Option B (8): Students may miscalculate
indexOf("IO")as 2 (off-by-one) giving 2+6=8. - Option C (7): Students may think
c.length()is 5 orindexOfis 2, yielding 7. - Option D (10): Students may think
indexOf("IO")is 4 (confusing with the original strings) giving 4+6=10.
Answer images

