String and ArrayList Methods Cheat Sheet for AP CSA

1. What You Need to Know

In AP CSA, Strings and ArrayLists show up everywhere: searching, slicing, building results, processing input, and writing clean loops. The exam expects you to be fluent with the Java Quick Reference methods (the ones guaranteed to exist on the exam) and the index rules that go with them.

The big ideas
  • String is immutable: you can’t change an existing String’s characters. Any “change” returns a new String.
  • ArrayList is mutable: you can change it (add/remove/set) and it shifts indices when you insert/remove.
  • Indices are zero-based for both:
    • First index is 0
    • Last index is length() - 1 (String) or size() - 1 (ArrayList)
AP CSA “guaranteed” methods (Quick Reference)

These are the methods you should assume are available on the exam without extra documentation:

  • String: length, substring, indexOf, compareTo, equals
  • ArrayList: size, add, get, set, remove

Important: You might know other Java methods (like charAt, contains, toLowerCase). On AP CSA, they’re not always assumed unless they appear in the question’s provided code/context. This sheet focuses on the guaranteed ones.


2. Step-by-Step Breakdown

A) Safely slicing Strings with substring

When you need “part of a String”:

  1. Decide start index (inclusive).
  2. Decide end index (exclusive) if using the 2-argument version.
  3. Use:
    • s.substring(start) to the end
    • s.substring(start, end) for a slice
  4. Double-check bounds:
    • 0 <= start <= end <= s.length()

Mini example

String s = "computer";
String a = s.substring(0, 3);   // "com"
String b = s.substring(3);      // "puter"
String c = s.substring(1, 5);   // "ompu"

Decision point: if you want the character at index k as a 1-length String, do:

String one = s.substring(k, k + 1);
B) Finding text with indexOf

When you need to locate a substring:

  1. Use int pos = s.indexOf(target);
  2. If pos == -1, it was not found.
  3. To find subsequent occurrences, restart searching after the previous match:
    • pos = s.indexOf(target, pos + 1);

Mini example: find all occurrences

String s = "bananas";
int pos = s.indexOf("an");
while (pos != -1) {
    System.out.println(pos);
    pos = s.indexOf("an", pos + 1);
}
// prints 1 then 3

Decision point: if you search for "" (empty string), Java returns 0 for indexOf("").

C) Modifying an ArrayList without skipping elements

When you remove items while looping, indices shift left.

Best approach for removals: loop backward

  1. Start at list.size() - 1
  2. Move down to 0
  3. Remove safely
for (int i = list.size() - 1; i >= 0; i--) {
    if (/* should remove list.get(i) */) {
        list.remove(i);
    }
}

Why backward works: removing index i doesn’t affect any indices < i that you still need to visit.

For insertions at specific positions: loop forward can work, but you must adjust i carefully (often i++ after an insert to avoid infinite loops).


3. Key Formulas, Rules & Facts

String methods (Java Quick Reference)
MethodWhat it doesKey rules / notesCommon AP use
s.length()number of charactersreturns intloop bounds, last index is length() - 1
s.substring(a)slice from a to enda must be from 0 to length()remove prefix, take suffix
s.substring(a, b)slice from a to b (exclusive)half-open interval [a, b)extract word/part
s.indexOf(str)first index where str startsreturns -1 if not foundsearch, validation
s.indexOf(str, fromIndex)search starting at fromIndexstill returns -1 if not foundfind next occurrence
s.compareTo(other)lexicographic comparenegative / 0 / positive (not necessarily -1/1)sorting, alphabetizing
s.equals(other)content equalityuse for Strings, not ==check exact match
String rules that show up as traps
  • substring(a, b) includes index a but not b.
  • substring can use b == s.length() (that’s valid).
  • indexOf searches for a substring, not a single character type; for a “character,” pass a 1-character String.
  • compareTo is based on Unicode/ASCII ordering (uppercase letters come before lowercase).
ArrayList methods (Java Quick Reference)

Assume ArrayList<E> list.

MethodWhat it doesReturnsIndex shifting?Notes
list.size()number of elementsintnolast index is size() - 1
list.add(obj)append to endbooleanno shift (adds at end)size increases by 1
list.add(i, obj)insert at index ivoidelements at i and after shift rightvalid i is 0..size
list.get(i)element at index iEnovalid i is 0..size-1
list.set(i, obj)replace element at iold Enosize unchanged
list.remove(i)remove at index iremoved Eelements after shift leftsize decreases by 1
ArrayList rules that show up as traps
  • add(i, obj) allows i == size() (inserting at the end). get(size()) is invalid.
  • remove(i) shifts everything after i left by 1.
  • set(i, obj) does not shift; it overwrites.
Types, generics, and autoboxing (quick but essential)
  • You declare element type: ArrayList<String> words = new ArrayList<String>();
  • You cannot store primitives directly: use wrapper classes.
    • ArrayList<Integer> instead of ArrayList<int>
  • Autoboxing/unboxing is automatic:
    • list.add(5); stores an Integer
    • int x = list.get(0); unboxes to int

4. Examples & Applications

Example 1: Build a new String by “removing” a character

Task: remove the character at index k from String s.

Key insight: Strings are immutable, so you rebuild with substrings.

String left = s.substring(0, k);
String right = s.substring(k + 1);
String result = left + right;

Works if k is in range 0..s.length() - 1.

Example 2: Check if a String contains a substring (using only Quick Reference)

Task: return true if s contains target.

Key insight: indexOf returns -1 if not found.

public boolean containsTarget(String s, String target) {
    return s.indexOf(target) != -1;
}

Exam variation: start searching after a certain point with indexOf(target, start).

Example 3: Remove all values less than 0 from an ArrayList

Key insight: remove shifts, so loop backward.

public void removeNegatives(ArrayList<Integer> nums) {
    for (int i = nums.size() - 1; i >= 0; i--) {
        if (nums.get(i) < 0) {
            nums.remove(i);
        }
    }
}

Exam variation: remove evens, remove duplicates, remove short Strings, etc.

Example 4: Insert into an ArrayList at a position

Task: insert "hi" at index 2.

words.add(2, "hi");

Key insight: old element at index 2 becomes index 3 (shift right).


5. Common Mistakes & Traps

  1. Using == instead of equals for Strings

    • What goes wrong: == checks if two variables reference the same object, not if the text matches.
    • Why wrong: two different String objects can contain identical characters.
    • Fix: use s.equals(t) (or t.equals(s) if s might be null).
  2. Off-by-one errors in substring(a, b)

    • What goes wrong: expecting b to be included.
    • Why wrong: the second index is exclusive.
    • Fix: if you want characters from a through b inclusive, use substring(a, b + 1).
  3. Forgetting indexOf can return -1

    • What goes wrong: using the result as an index immediately.
    • Why wrong: -1 is not a valid index.
    • Fix: always check if (pos != -1) before using it.
  4. Assuming compareTo returns only -1, 0, or 1

    • What goes wrong: code like if (s.compareTo(t) == 1).
    • Why wrong: it can return any positive/negative integer.
    • Fix: use < 0, == 0, > 0.
  5. Removing from an ArrayList while looping forward

    • What goes wrong: skipping elements after a removal.
    • Why wrong: elements shift left; your loop counter still increments.
    • Fix: loop backward for removals, or decrement i after removing.
  6. Confusing add(i, x) with set(i, x)

    • What goes wrong: using set expecting an insertion (or add expecting replacement).
    • Why wrong: add shifts and grows; set overwrites without changing size.
    • Fix: remember: add = insert, set = swap/replace.
  7. Index bound errors (size() vs last valid index)

    • What goes wrong: using i <= list.size() or list.get(list.size()).
    • Why wrong: last valid index is size() - 1.
    • Fix: loop condition should usually be i < list.size().
  8. Thinking Strings can be modified in place

    • What goes wrong: calling s.substring(...) but not storing the result.
    • Why wrong: the original s is unchanged.
    • Fix: assign back: s = s.substring(...);

Warning: Any invalid index for substring, get, set, add(i, ...), or remove causes an IndexOutOfBoundsException (or StringIndexOutOfBoundsException) in real Java. On the exam, they love testing whether you know what indices are legal.


6. Memory Aids & Quick Tricks

Trick / mnemonicWhat it helps you rememberWhen to use it
“Substrings are [start, end)”start included, end excludedany substring(a, b) boundary check
“IndexOf: -1 means no”indexOf failure signalsearching / validating existence
“CompareTo gives sign, not size”use < 0, == 0, > 0 (not == 1)String ordering logic
“Add inserts, Set swaps”add(i, x) shifts; set(i, x) replacesArrayList updates
“Remove? Go in reverse”avoid skipping due to shiftingfiltering ArrayLists
“Size is a count, not an index”last index is size() - 1loop bounds and indexing

7. Quick Review Checklist

  • Strings

    • You use equals, not ==, for text equality.
    • substring(a, b) includes a but excludes b.
    • indexOf(...) returns -1 if not found.
    • compareTo returns negative/zero/positive; check with < 0, == 0, > 0.
    • Strings don’t change unless you reassign the returned value.
  • ArrayLists

    • Last valid index is size() - 1.
    • add(obj) appends; add(i, obj) inserts and shifts right.
    • set(i, obj) replaces and does not change size.
    • remove(i) shifts left; loop backward when removing many.
    • Use ArrayList<Integer> (wrapper) for numbers, not primitives.

You’ve got this—if you can track indices and shifting confidently, Strings and ArrayLists become easy points.