APrep Open the app

AP Computer Science A · Unit 2: Selection & Iteration

2.10 Developing Algorithms Using Strings

Traversing strings with loops

Common String algorithms use loops to visit each character with `.charAt(i)` from `i = 0` to `str.length() - 1`. Typical tasks include counting occurrences of a character, finding the first/last index of a value, building a new string, or checking properties like palindromes. Always watch loop bounds to avoid IndexOutOfBoundsException.

Building & comparing strings

Strings are immutable — methods like `.substring()` and `.concat()` return a new String rather than modifying the original. Concatenation with `+=` in a loop is a common pattern to build results. Use `.equals()` for value comparison (not `==`, which compares references) and `.compareTo()` for lexicographic ordering.

Useful String methods for algorithms

Key methods: `.length()`, `.charAt(index)`, `.substring(start, end)`, `.indexOf(str)`, `.equals(other)`, and `.compareTo(other)`. Combining these with loops and conditionals lets you solve problems like reversing a string, counting vowels, or checking if one string contains another.

Key terms

charAt(index)
Returns the character at the specified index in a String.
substring(start, end)
Returns a new String containing characters from start up to but not including end.
indexOf(str)
Returns the index of the first occurrence of str, or -1 if not found.
equals() vs ==
equals() compares character content; == compares object references.
String immutability
Strings cannot be changed after creation; methods like substring() and concat() return new String objects.

Try an AP-style question

Code

String s = "hello";
String r = "";
for (int i = s.length() - 1; i >= 0; i--)
    r += s.substring(i, i + 1);

What is r?

  1. "olle"
  2. "hello"
  3. "olleh"
  4. An error
Show the answer

C. Builds the reverse.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 2.10 free in APrep