Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

4.1: String Indexing

A String of length n has valid character indices 0 through n - 1. Use substring(i, i + 1) to obtain a one-character String.

College Board Unit 1

How it works

Characters occupy indexes 0 through s.length() - 1. The call s.substring(i, i + 1) returns the character at index i as a one-character String. For s.substring(from, to), valid bounds satisfy 0 <= from <= to <= s.length(). Equal endpoints return the empty String, and s.substring(s.length()) is also valid and empty. String length() is a method; array length is a field.

Write indexes beneath the characters and check both boundaries of each substring call.

Common error

s.substring(s.length()) is valid and empty; s.substring(s.length(), s.length() + 1) throws because its end is too large.

Worked example

Java

String word = "JAVA";
System.out.println(word.length());
System.out.println(word.substring(3, 4));

Output

4
A

Length counts characters; the final valid position is one less than the length.

Exercises

4.1.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

String word = "code";
System.out.println(word.substring(0, 1) + word.substring(word.length() - 1));
Show solution

Output

ce

The first slice includes index 0 only. The one-argument slice continues from index 3 to the end.

4.1.2 · Write code

Write public static String ends(String text). Assume text is nonempty. Return the first and last characters joined together; a one-character input contributes that character twice.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static String ends(String text) {
    return text.substring(0, 1) + text.substring(text.length() - 1);
}

Check your code

Java

System.out.println(ends("Java"));
System.out.println(ends("Q"));

Expected output

Ja
QQ
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic