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) orsize() - 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”:
- Decide start index (inclusive).
- Decide end index (exclusive) if using the 2-argument version.
- Use:
s.substring(start)to the ends.substring(start, end)for a slice
- 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:
- Use
int pos = s.indexOf(target); - If
pos == -1, it was not found. - 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
- Start at
list.size() - 1 - Move down to 0
- 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)
| Method | What it does | Key rules / notes | Common AP use |
|---|---|---|---|
s.length() | number of characters | returns int | loop bounds, last index is length() - 1 |
s.substring(a) | slice from a to end | a 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 starts | returns -1 if not found | search, validation |
s.indexOf(str, fromIndex) | search starting at fromIndex | still returns -1 if not found | find next occurrence |
s.compareTo(other) | lexicographic compare | negative / 0 / positive (not necessarily -1/1) | sorting, alphabetizing |
s.equals(other) | content equality | use for Strings, not == | check exact match |
String rules that show up as traps
substring(a, b)includes indexabut notb.substringcan useb == s.length()(that’s valid).indexOfsearches for a substring, not a single character type; for a “character,” pass a 1-character String.compareTois based on Unicode/ASCII ordering (uppercase letters come before lowercase).
ArrayList methods (Java Quick Reference)
Assume ArrayList<E> list.
| Method | What it does | Returns | Index shifting? | Notes |
|---|---|---|---|---|
list.size() | number of elements | int | no | last index is size() - 1 |
list.add(obj) | append to end | boolean | no shift (adds at end) | size increases by 1 |
list.add(i, obj) | insert at index i | void | elements at i and after shift right | valid i is 0..size |
list.get(i) | element at index i | E | no | valid i is 0..size-1 |
list.set(i, obj) | replace element at i | old E | no | size unchanged |
list.remove(i) | remove at index i | removed E | elements after shift left | size decreases by 1 |
ArrayList rules that show up as traps
add(i, obj)allowsi == size()(inserting at the end).get(size())is invalid.remove(i)shifts everything afterileft 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 ofArrayList<int>
- Autoboxing/unboxing is automatic:
list.add(5);stores anIntegerint x = list.get(0);unboxes toint
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
Using
==instead ofequalsfor 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)(ort.equals(s)ifsmight benull).
- What goes wrong:
Off-by-one errors in
substring(a, b)- What goes wrong: expecting
bto be included. - Why wrong: the second index is exclusive.
- Fix: if you want characters from
athroughbinclusive, usesubstring(a, b + 1).
- What goes wrong: expecting
Forgetting
indexOfcan return-1- What goes wrong: using the result as an index immediately.
- Why wrong:
-1is not a valid index. - Fix: always check
if (pos != -1)before using it.
Assuming
compareToreturns only-1,0, or1- What goes wrong: code like
if (s.compareTo(t) == 1). - Why wrong: it can return any positive/negative integer.
- Fix: use
< 0,== 0,> 0.
- What goes wrong: code like
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
iafter removing.
Confusing
add(i, x)withset(i, x)- What goes wrong: using
setexpecting an insertion (oraddexpecting replacement). - Why wrong:
addshifts and grows;setoverwrites without changing size. - Fix: remember: add = insert, set = swap/replace.
- What goes wrong: using
Index bound errors (
size()vs last valid index)- What goes wrong: using
i <= list.size()orlist.get(list.size()). - Why wrong: last valid index is
size() - 1. - Fix: loop condition should usually be
i < list.size().
- What goes wrong: using
Thinking Strings can be modified in place
- What goes wrong: calling
s.substring(...)but not storing the result. - Why wrong: the original
sis unchanged. - Fix: assign back:
s = s.substring(...);
- What goes wrong: calling
Warning: Any invalid index for
substring,get,set,add(i, ...), orremovecauses anIndexOutOfBoundsException(orStringIndexOutOfBoundsException) in real Java. On the exam, they love testing whether you know what indices are legal.
6. Memory Aids & Quick Tricks
| Trick / mnemonic | What it helps you remember | When to use it |
|---|---|---|
| “Substrings are [start, end)” | start included, end excluded | any substring(a, b) boundary check |
| “IndexOf: -1 means no” | indexOf failure signal | searching / 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) replaces | ArrayList updates |
| “Remove? Go in reverse” | avoid skipping due to shifting | filtering ArrayLists |
| “Size is a count, not an index” | last index is size() - 1 | loop bounds and indexing |
7. Quick Review Checklist
Strings
- You use
equals, not==, for text equality. substring(a, b)includesabut excludesb.indexOf(...)returns-1if not found.compareToreturns negative/zero/positive; check with< 0,== 0,> 0.- Strings don’t change unless you reassign the returned value.
- You use
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.
- Last valid index is
You’ve got this—if you can track indices and shifting confidently, Strings and ArrayLists become easy points.