Skip to main content

Unit 1 · Using Objects and Methods

substring and indexOf

Practice mode with 15 Java-focused questions, immediate answer checks, and explanations.

What substring and indexof covers

The call substring(a, b) returns characters from index a up to but not including index b, so the result has b - a characters. The one-argument form substring(a) runs from index a to the end of the String. The indexOf method returns the index of the first occurrence of a target, or -1 when the target does not appear at all.

Where students lose points

Treating the end index as inclusive is the dominant error and produces an answer one character too long. The other frequent failure is passing an unchecked indexOf result straight into substring: when indexOf returns -1 the substring call throws. Students also forget that substring(a, a) legally returns an empty String.

How it shows up on the AP exam

Unit 1 String methods, and a heavily tested combination because a single line can test index arithmetic, method semantics, and boundary handling at once. Word- and token-parsing FRQs lean on it directly.

For practice use only.

substring and indexOf MCQ Practice

AP CSA substring and indexOf practice: inclusive start and exclusive end, computing result length, and handling the -1 that indexOf returns when nothing matches.

Question 1 of 15

Answered 0 of 15

Choose one answer.

Which option matches the complete output produced by this segment?

public class SubstringAndIndexOfContext
{
    public static void runExample()
    {
        String s = "alphabet";
        System.out.print(s.indexOf("ph"));
    }

    public static void main(String[] args)
    {
        runExample();
    }
}
Choose one answer.