Unit 1 Cycle 2 Day 9: Nested Method Calls and String Building

Unit 1 Advanced (Cycle 2) Day 9 of 28 Advanced

Nested Method Calls and String Building

Section 1.10 — Strings: Methods

Key Concept

Nested method calls evaluate from the innermost call outward. In s.substring(s.indexOf("x"), s.length()), Java first evaluates s.indexOf("x") and s.length(), then passes those results to substring(). The AP exam creates complex nesting where the return value of one method becomes the argument to another. Trace these by evaluating each method call separately, writing down the intermediate result, then substituting it back into the outer expression.

Consider the following code segment.

String s = "PROGRAMMING"; String r = s.substring(0, 3) + s.substring(s.indexOf("M")); System.out.println(r + " " + r.length());

What is printed as a result of executing the code segment?

Answer: (A) PROMMING 8

Index: P(0) R(1) O(2) G(3) R(4) A(5) M(6) M(7) I(8) N(9) G(10)

substring(0, 3): Characters 0-2 = "PRO".

indexOf("M"): First "M" is at index 6.

substring(6): Characters from index 6 onward = "MMING".

r: "PRO" + "MMING" = "PROMMING" (8 characters).

Output: PROMMING 8

Why Not the Others?

(B) This would require substring(5) instead of substring(6). indexOf("M") returns 6 (the first M), not 5 (the A).

(C) This would mean no characters were removed, but substring(0,3) only takes the first 3 characters, skipping "GRA" in the middle.

(D) The length is 8, not 7. "PRO" has 3 characters and "MMING" has 5 characters: 3 + 5 = 8.

Common Mistake

Carefully count the characters at each step. substring(0, 3) gives 3 characters (indices 0, 1, 2). substring(6) gives 5 characters (indices 6, 7, 8, 9, 10). The middle section (indices 3-5: "GRA") is skipped.

AP Exam Tip

Write out the full string with index numbers. Circle the portions selected by each substring call. What remains is the result. This visual approach prevents counting errors.

Review this topic: Section 1.10 — Strings: Methods • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.