AP Computer Science AUnit 1 · Using Objects and Methods
String Objects and Methods
Create and use String objects, apply the methods in the AP Java subset, compare strings correctly, and understand immutability.
Strings are objects
String s = "hello"; creates a String object. Strings are immutable: methods return new strings and never change the original.
Methods in the AP subset
| Method | Returns |
|---|---|
length() | number of characters |
substring(a, b) | characters from index a up to, not including, b |
substring(a) | from index a to the end |
indexOf(str) | first index of str, or -1 if not found |
equals(other) | true if the characters are the same |
compareTo(other) | negative, zero or positive (dictionary order) |
Indexes start at 0; the last index is length() - 1. Using an index out of range throws a StringIndexOutOfBoundsException.
Examples
String w = "computer";
w.length() // 8
w.substring(3, 6) // "put"
w.substring(5) // "ter"
w.indexOf("m") // 2
w.indexOf("z") // -1
One character as a string: w.substring(i, i + 1).
Comparing strings
- Use
equalsto compare contents. ==compares references and can give false even when the text is the same."apple".compareTo("banana")is negative because "apple" comes first.
Concatenation
"Score: " + 5 + 3 is "Score: 53" (left to right, string first). 5 + 3 + " points" is "8 points".
Quick summary
- Indexes 0 to length() - 1; substring end is exclusive.
- Strings never change; reassign to keep a result.
- Compare with equals and compareTo, not ==.
Topic quiz
5 questions. You need at least 80% correct to pass; passing unlocks the next topic.
Log in to take the quiz and save your progress. Creating an account is free.
Log in and take the quiz