AP CSA Unit 1 Built-In Classes: Strings, Math, APIs, and Comments
String Methods
What a String is (and why built-in methods matter)
In AP Computer Science A, a String is an object that represents a sequence of characters (letters, digits, punctuation, spaces). You use strings constantly—printing messages, reading user input (in later units), storing names, searching text, and formatting output. Because strings are so common, Java provides a built-in class String with many useful methods.
A key idea: a String is not a primitive like int or double. It’s an object, which means:
- You create and manipulate it using constructors (rarely needed directly for
String) and methods. - Variables of type
Stringhold a reference to aStringobject.
Even more important: Strings are immutable. Immutable means once a String object is created, it can’t be changed. If you “modify” a string (like making it uppercase or taking a substring), Java actually creates a new String object and gives you a reference to that new object.
Why this matters: many bugs in beginner code come from calling a string method and assuming it changed the original string. It didn’t—you must store or use the returned value.
Creating and combining strings
You’ll most often create strings using string literals:
String name = "Ava";
String empty = "";
You can concatenate (join) strings with the + operator:
String message = "Hello, " + name; // "Hello, Ava"
If one side of + is a String, Java converts the other side to a string (this is called string conversion):
int score = 42;
String s = "Score: " + score; // "Score: 42"
A common pitfall is evaluation order with +:
System.out.println("Sum: " + 2 + 3); // "Sum: 23"
System.out.println("Sum: " + (2 + 3)); // "Sum: 5"
In the first line, Java starts concatenating as soon as it sees a String, so 2 and 3 become text.
Core String methods you’re expected to use
AP CSA emphasizes a standard set of String methods (as reflected on the Java Quick Reference used for the exam). You should understand what each does, what it returns, and what common mistakes look like.
length()
What it is: length() returns the number of characters in the string.
Why it matters: You use it for bounds in loops, validating input lengths, and indexing.
How it works: It counts every character including spaces and punctuation.
String word = "computer";
int n = word.length(); // 8
What goes wrong: Off-by-one indexing mistakes. Valid indices are 0 through length() - 1.
substring(int from, int to) and substring(int from)
What it is: substring returns a new string that is a slice of the original.
Why it matters: Substrings are central to text processing—extracting first names, area codes, file extensions, etc.
How it works (very important):
substring(from, to)includes the character at indexfrom.- It stops before index
to(sotois exclusive). substring(from)goes fromfromto the end.
String s = "holiday";
String a = s.substring(1, 4); // "oli" (indices 1,2,3)
String b = s.substring(3); // "iday"
What goes wrong:
- Treating
toas inclusive. - Using an index outside
0..length()(this causes aStringIndexOutOfBoundsException).
A good habit is to say out loud: “start at from, stop before to.”
indexOf(String str) and indexOf(String str, int fromIndex)
What it is: indexOf searches for a substring and returns the index of the first occurrence.
Why it matters: Searching is a foundational skill for many later tasks (parsing, validation, repeated patterns).
How it works:
- If the substring is found, you get the starting index.
- If it is not found, you get
-1. - The overload with
fromIndexstarts searching at that index.
String text = "bananas";
int i1 = text.indexOf("na"); // 2
int i2 = text.indexOf("na", 3); // 4
int i3 = text.indexOf("apple"); // -1
What goes wrong: Forgetting about the -1 case. On exam-style questions, you often must check for -1 before using the index.
equals(String other)
What it is: equals checks whether two strings have the same characters in the same order.
Why it matters: This is the correct way to compare string contents.
How it works: It returns a boolean.
String a = "hi";
String b = "hi";
System.out.println(a.equals(b)); // true
What goes wrong (major): Using == instead of equals.
==compares whether two references point to the exact same object.equalscompares the contents.
Sometimes == appears to “work” with string literals because of Java’s internal optimizations, but you must not rely on that—AP questions are designed to test that you know the difference.
compareTo(String other)
What it is: compareTo compares strings in lexicographic (dictionary) order.
Why it matters: It’s the backbone of sorting and ordering.
How it works:
- Returns a value less than 0 if
thisstring comes beforeother. - Returns 0 if they are equal.
- Returns a value greater than 0 if
thiscomes afterother.
System.out.println("apple".compareTo("banana")); // negative
System.out.println("same".compareTo("same")); // 0
System.out.println("dog".compareTo("cat")); // positive
Case sensitivity: Capital letters come before lowercase letters in Unicode/ASCII-based ordering, so:
System.out.println("Zoo".compareTo("apple")); // typically negative because 'Z' < 'a'
What goes wrong:
- Thinking the result is always
-1,0, or1. It can be any negative or positive integer. - Forgetting case sensitivity.
Strings, methods, and immutability in action
Because strings are immutable, you must capture returned results:
String s = "ap";
s.concat("cs");
System.out.println(s); // still "ap" (concat returns a new String, but we ignored it)
s = s + "cs";
System.out.println(s); // "apcs"
Even though concat exists in Java, AP CSA commonly uses + for concatenation. The bigger lesson is the same: methods often return new values rather than modifying the original object.
Worked example: extracting parts of a formatted ID
Suppose an ID is formatted like "NY-48392".
Goal: extract the state code ("NY") and the number part ("48392").
Reasoning:
- The hyphen is at index
2. - State is from
0up to (but not including) the hyphen. - Number is from one after the hyphen to the end.
String id = "NY-48392";
int dash = id.indexOf("-");
String state = id.substring(0, dash);
String number = id.substring(dash + 1);
System.out.println(state); // NY
System.out.println(number); // 48392
Notice the safe pattern: find an index with indexOf, then use that index to choose substring boundaries.
Exam Focus
- Typical question patterns:
- Trace code that uses
substring,indexOf, andlength()to compute output. - Choose the correct substring boundaries when extracting pieces of a string.
- Determine whether
equals,==, orcompareTois appropriate in a given scenario.
- Trace code that uses
- Common mistakes:
- Treating
substring(from, to)as including indexto(it doesn’t). - Using
==for content comparison instead ofequals. - Forgetting
indexOfcan return-1, then using-1as a substring index.
- Treating
Using the Math Class
What Math is (and why it’s designed differently)
Java’s Math class provides common mathematical operations like square roots, powers, absolute value, and random numbers. In AP CSA, Math is important because it’s one of your first examples of a utility class—a class that mainly offers tools rather than representing “objects you create.”
The big design feature: most Math methods are static.
- Static method means you call it using the class name, not an instance.
- You do not write
new Math().
So you write:
double r = Math.sqrt(81); // 9.0
This connects directly to Unit 1’s focus: you are learning how to use existing classes by calling their methods correctly.
Core Math methods in AP CSA
AP CSA emphasizes a small set of Math methods (as on the Java Quick Reference).
Math.abs(x)
What it is: Returns the absolute value (distance from zero).
Why it matters: Often used in comparisons, error margins, and handling negatives.
int a = Math.abs(-7); // 7
double b = Math.abs(-2.5); // 2.5
What goes wrong: Assuming it changes the original variable—like all methods, it returns a value; you must store/use it.
Math.pow(a, b)
What it is: Returns a^b as a double.
Why it matters: Useful for exponential growth, area/volume formulas, and computations.
double x = Math.pow(2, 3); // 8.0
What goes wrong:
- Forgetting the result is a
doubleeven if both inputs look like integers. - Expecting exact integer precision for large values (floating-point rounding can appear).
Math.sqrt(x)
What it is: Returns the square root of x as a double.
double s = Math.sqrt(49); // 7.0
What goes wrong:
- Taking square roots of negative numbers yields
NaN(not a number) in Java.
Math.random()
What it is: Returns a pseudorandom double in the range [0.0, 1.0).
- Inclusive of
0.0 - Exclusive of
1.0
Why it matters: Randomness is frequently used in simulations and games, and AP CSA loves testing whether you understand the boundaries.
double r = Math.random();
// 0.0 <= r < 1.0
Getting random integers in a range (a must-know skill)
Most programs need random integers, not random doubles. The standard approach is:
- Scale
Math.random()by the size of the range. - Convert to
intto drop the decimal part. - Shift by the minimum value.
For integers from 0 to n - 1 (n values):
int n = 6;
int roll = (int)(Math.random() * n); // 0..5
For integers from 1 to n:
int n = 6;
int roll = (int)(Math.random() * n) + 1; // 1..6
For integers from min to max inclusive:
- There are
max - min + 1possible integers.
int min = 10;
int max = 15;
int value = (int)(Math.random() * (max - min + 1)) + min; // 10..15
Why the cast is placed where it is: (int) truncates toward 0. You want to truncate after scaling, not before.
Bad pattern:
(int)Math.random() * 6 // always 0 because (int)Math.random() is always 0
Worked example: simulating two dice
You want two integers each from 1 to 6.
int die1 = (int)(Math.random() * 6) + 1;
int die2 = (int)(Math.random() * 6) + 1;
int sum = die1 + die2;
System.out.println(sum);
Key reasoning: Math.random() * 6 produces a double from 0.0 up to (but not including) 6.0. Casting truncates to 0–5, then adding 1 shifts to 1–6.
Exam Focus
- Typical question patterns:
- Determine the range of values produced by an expression using
Math.random(). - Trace code that mixes
intanddoublewithMath.pow/Math.sqrtand identify the printed output. - Choose the correct expression to generate a random integer in a specified range.
- Determine the range of values produced by an expression using
- Common mistakes:
- Casting too early:
(int)Math.random()is always0. - Forgetting
Math.random()never returns1.0, which affects upper bounds. - Assuming
Math.powreturns anintwhen it returns adouble.
- Casting too early:
API and Libraries
What an API is in Java
An API (Application Programming Interface) is the set of classes, methods, and rules that let you use code written by someone else. In Java, the API is huge: thousands of built-in classes for strings, math, collections, input/output, graphics, and more.
In AP CSA Unit 1, you’re building the habit of reading a class’s available constructors and methods and then calling them correctly. You are essentially learning to “drive” classes you didn’t write.
Libraries, packages, and imports
A library is a collection of related classes. In Java, classes are organized into packages (folders/namespaces). For example:
java.langincludesString,Math, andSystem.- Many other packages exist, like
java.util.
Some packages are automatically available:
java.langis imported by default, which is why you can useStringandMathwithout writing animportstatement.
To use classes from other packages, you typically import them:
import java.util.Scanner;
This tells Java where to find the class name Scanner.
How to read documentation like a programmer
When you look at documentation (or the AP Java Quick Reference), focus on the “contract” of a method:
- Method name: what capability it provides.
- Parameter list: what inputs it needs and their types.
- Return type: what you get back (or
voidif nothing). - Description: details like edge cases, index rules, ranges, or special return values.
A method signature example:
int indexOf(String str)
From this, you should infer:
- You call it on a
Stringobject. - You pass a
Stringargument. - You get back an
int(an index).
Static vs instance methods (and how questions try to trick you)
One of the most testable skills in Unit 1 is distinguishing:
- Instance methods: called on an object (like
s.length()wheresis aString). - Static methods: called on the class (like
Math.random()).
If you write Math m = new Math();, that’s a red flag—Math is not meant to be instantiated.
Overloading: same name, different parameters
Java allows method overloading, meaning two methods can have the same name but different parameter lists.
You’ve already seen this with substring and indexOf:
substring(int from)substring(int from, int to)
Overloading matters because on multiple-choice questions you may need to choose which call is valid based on argument types and count.
Using the AP Java Quick Reference effectively
On the AP exam, you’re given a subset reference sheet listing certain classes and methods. The exam expects you to:
- Recognize methods available for
StringandMath. - Apply them correctly in short code segments.
- Reason about return values and edge cases.
A smart approach when you’re unsure:
- Identify the object’s type.
- Identify whether the method is static or instance.
- Match argument types/count.
- Check the return type and use it appropriately.
Worked example: choosing the right tool from the API
Task: You want to check whether two strings represent the same word.
Bad approach: ==
if (a == b) { ... } // compares references, not contents
Correct approach: use the API contract of equals:
if (a.equals(b)) {
System.out.println("Match");
}
Here, you’re relying on the documented behavior of String.equals to compare contents.
Exam Focus
- Typical question patterns:
- Identify whether a method call is valid based on parameter types and return type.
- Distinguish static calls (like
Math.random()) from instance calls (likestr.substring(...)). - Use the Quick Reference to predict outputs of code using listed methods.
- Common mistakes:
- Calling an instance method as if it were static (or vice versa).
- Ignoring the return type (for example, treating
indexOfas if it returns aboolean). - Confusing overloaded methods and supplying the wrong number/type of arguments.
Documentation With Comments
What comments are (and what they are not)
Comments are notes you write in code for humans. The compiler ignores them, so they do not change what the program does. Their purpose is communication: to your future self, to classmates, and (in real software) to teammates who need to maintain or extend your code.
In AP CSA, good commenting supports two big goals:
- Clarity while you learn: you can explain what each part is supposed to do.
- Documentation of intent: you can state assumptions, preconditions, and expected behavior.
A common misconception is that “more comments is always better.” Comments should add information that is not already obvious from clean code. If you rename variables well and keep methods focused, you often need fewer comments.
The three main comment styles in Java
Single-line comments: //
Use these for short explanations, especially for a tricky line.
int total = a + b; // sum of two values
Block comments: /* ... */
Use these for multi-line notes, often at the top of a file or to describe a larger chunk of logic.
/*
This program simulates rolling a die.
It prints a number from 1 to 6.
*/
Documentation comments (Javadoc): /** ... */
Javadoc comments are a special kind of block comment intended to generate HTML documentation. In many Java codebases, this is how APIs are documented.
Even if AP CSA doesn’t require you to generate documentation, the style is useful because it encourages you to describe:
- What a method does
- What parameters mean
- What is returned
Example:
/**
* Returns the larger of two integers.
* @param a the first integer
* @param b the second integer
* @return the larger value
*/
public static int max(int a, int b) {
if (a > b) {
return a;
}
return b;
}
Commenting to explain “why,” not “what”
The best comments explain intent and reasoning.
Less helpful (states the obvious):
// adds 1 to x
x = x + 1;
More helpful (explains why you’re doing it):
// Move to the next character to avoid processing the same one twice
index = index + 1;
Preconditions and postconditions (useful for reasoning)
When you write methods (more emphasized later in the course), good documentation often includes:
- Precondition: what must be true before the method is called.
- Postcondition: what the method guarantees after it finishes.
Even in Unit 1, you can think this way when using built-in methods.
Example: For substring(from, to), a precondition is that 0 <= from <= to <= length().
Thinking in preconditions helps you avoid runtime errors like out-of-bounds indices.
Commenting and debugging: preventing logic errors
Comments can prevent subtle mistakes, especially with indices. For example, when using substring, it’s easy to forget “end is exclusive.” A short comment near complex index math can save you.
// Extract characters 0..2 (end index 3 is exclusive)
String prefix = s.substring(0, 3);
Just be careful: outdated comments are worse than no comments. If you change code, update or remove comments that no longer apply.
Worked example: documenting string parsing
/**
* Extracts the username from an email address of the form name@domain.
* Precondition: email contains an '@' character.
*/
public static String getUser(String email) {
int at = email.indexOf("@");
// Username is everything before '@'
return email.substring(0, at);
}
This comment documents an important precondition: if '@' isn’t present, indexOf returns -1 and substring(0, -1) would crash.
Exam Focus
- Typical question patterns:
- Interpret what code is intended to do based on comments (especially in longer free-response style prompts).
- Decide which comment best describes a block of code or a method’s purpose.
- Use comments to understand preconditions (like valid index ranges) in trace problems.
- Common mistakes:
- Writing comments that contradict the code (often due to editing code and not updating comments).
- Using comments as a substitute for meaningful names (better: rename variables/methods).
- Missing key assumptions (like “the string contains a dash”) that should be documented or checked in code.