AP CSA Unit 1 Day 26: Tracing Concat Methods

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

Tracing Concatenation with Method Returns

Section Mixed — Review: Strings and Methods

Key Concept

Tracing concatenation with method return values requires understanding that method calls are evaluated before the concatenation occurs. In "Result: " + obj.getValue() + obj.update(), both method calls execute left to right, and their return values are converted to strings and concatenated. If update() modifies state that getValue() depends on, the order of evaluation matters. The AP exam tests this by having methods with side effects participate in concatenation expressions.

Consider the following code segment.

String s = "TESTING"; int a = s.length(); int b = s.indexOf("T", 1); String sub = s.substring(b, a); System.out.println(sub + " " + sub.length());

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

Answer: (A) TING 4

Index: T(0) E(1) S(2) T(3) I(4) N(5) G(6). Length = 7.

a: s.length() = 7.

b: s.indexOf("T", 1) searches for "T" starting from index 1. Skips T at index 0, finds T at index 3. So b = 3.

sub: substring(3, 7) = characters at indices 3, 4, 5, 6 = "TING" (4 characters).

Output: "TING 4".

Why Not the Others?

(B) The result has 4 characters, not 5.

(C) The search starts from index 1, finding T at index 3, not S at index 2.

(D) The substring starts at index 3, not index 0.

Common Mistake

The two-argument indexOf method starts searching from the specified index. indexOf("T", 1) skips the first T at index 0 and finds the next T at index 3. This is useful for finding the second occurrence of a character.

AP Exam Tip

The two-argument form of indexOf(target, fromIndex) is on the AP Quick Reference sheet. It starts searching at fromIndex, which is useful for finding subsequent occurrences after the first.

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

More Practice

Back to blog

Leave a comment

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