TLDR
String manipulation in AP Computer Science A means creating String objects and using built-in methods like length, substring, indexOf, equals, and compareTo to work with text. The big idea is that Strings are immutable, so methods return new String objects instead of changing the original. You combine Strings with the + and += operators, and indices run from 0 to length() - 1.

Why This Matters for the AP Computer Science A Exam
String work shows up across the exam. In multiple-choice questions, you trace concatenation, predict what substring returns, and figure out the result of indexOf and equals. In free-response code writing, the first question focuses on methods and control structures, and that question type can require you to call String methods inside an algorithm. The String methods tested here are listed in the Java Quick Reference, so practice using that resource the way you will on exam day. Getting comfortable with zero-based indexing, exclusive end indices, and immutability now prevents avoidable mistakes later.
Key Takeaways
- Create Strings with a literal like
"Alice"or with theStringconstructor; literals are the normal choice, andStringis available by default fromjava.lang. - Strings are immutable, so capture the return value of any String method if you want to use the result.
- Concatenation with
+or+=builds a new String, and a primitive joined to a String is converted to a String automatically. - Valid indices run from 0 to
length() - 1; going outside that range throws aStringIndexOutOfBoundsException. substring(from, to)includesfrombut excludesto, so the result hasto - fromcharacters.- Use
equalsto compare String contents andcompareToto order Strings alphabetically; never use==to compare contents.
Creating String Objects
A String object holds a sequence of characters. You can create one with a string literal:
</>JavaString name = "Alice";
You can also call the String constructor:
</>JavaString name = new String("Alice");
The literal form is the normal choice and reads more cleanly. The String class is part of java.lang, so it is available by default with no import. Strings are so common in programming that you will use them in nearly every program.
String Concatenation
The + operator with Strings joins them together. Writing "Hello" + "World" produces a new String "HelloWorld". This is called concatenation.
When you concatenate a primitive value with a String, Java converts the primitive to a String automatically. So "Score: " + 95 produces "Score: 95". Concatenating any object with a String implicitly calls that object's toString method to get its String form.
The += operator appends to an existing String variable:
</>JavaString message = "Hello"; message += " there"; // message now refers to "Hello there"
Because Strings are immutable, += does not change the original String object. It creates a new String and reassigns the variable.
Understanding String Indices
Every character in a String has an index, starting at 0. In "Hello", 'H' is at index 0 and 'o' is at index 4. The last character is always at index length() - 1.
This zero-based indexing matches how arrays work. If you access an index that is negative or greater than or equal to the length, you get a StringIndexOutOfBoundsException, which is a run-time error.
Essential String Methods
These methods are part of the Java Quick Reference you will have on the exam.
int length() returns the number of characters in the String. An empty String "" has length 0.
String substring(int from, int to) returns the substring beginning at index from and ending at index to - 1. The character at to is not included, so "Hello".substring(1, 4) returns "ell" (indices 1, 2, and 3).
String substring(int from) returns the substring from from to the end of the String. It is the same as substring(from, length()).
int indexOf(String str) returns the index of the first occurrence of str, or -1 if str is not found. The -1 return value is the standard way to check whether something exists in a String.
boolean equals(Object other) returns true if the two Strings have the same sequence of characters and false otherwise. This is the correct way to compare String contents.
int compareTo(String other) returns a value less than 0 if this String comes before other, zero if they are equal, and a value greater than 0 if this String comes after other. Strings are ordered based on the alphabet.
A single-character String at a given index can be created with substring(index, index + 1).
Working with Immutability
Immutability means a String object never changes after it is created. When you call a method on a String, you get a new String back; the original is untouched.
This makes Strings safe to pass around and share, since no method can alter them. The practical rule: always capture the return value if you want the result.
</>JavaString text = "alice"; text.substring(0, 1); // result is discarded, text is unchanged String first = text.substring(0, 1); // captures "a"
Code Examples
String creation and basic methods:
</>Javapublic class StringBasics { public static void main(String[] args) { // Create strings using literals (most common) String greeting = "Hello World"; String empty = ""; // Valid empty string // Using length() method System.out.println(greeting.length()); // 11 System.out.println(empty.length()); // 0 // Concatenation examples String firstName = "Alice"; String lastName = "Smith"; String fullName = firstName + " " + lastName; // "Alice Smith" // Concatenation with a primitive value int score = 95; String result = "Your score: " + score + "%"; // "Your score: 95%" // Using += operator String message = "Hello"; message += " there"; // Creates new string "Hello there" System.out.println(message); } }
Using substring to extract parts of strings:
</>Javapublic class SubstringDemo { public static void main(String[] args) { String email = "student@school.edu"; // Find username before the @ symbol int atIndex = email.indexOf("@"); String username = email.substring(0, atIndex); // "student" // Extract domain after the @ symbol String domain = email.substring(atIndex + 1); // "school.edu" // Extract file extension String filename = "document.pdf"; int dotIndex = filename.indexOf("."); String extension = filename.substring(dotIndex + 1); // "pdf" // Working with fixed positions String phoneNumber = "123-456-7890"; String areaCode = phoneNumber.substring(0, 3); // "123" String exchange = phoneNumber.substring(4, 7); // "456" String number = phoneNumber.substring(8); // "7890" } }
Searching and comparison:
</>Javapublic class StringSearching { public static void main(String[] args) { String sentence = "The quick brown fox jumps over the lazy dog"; // Using indexOf to search int foxIndex = sentence.indexOf("fox"); // 16 int catIndex = sentence.indexOf("cat"); // -1 (not found) // Check if substring exists if (sentence.indexOf("quick") != -1) { System.out.println("Found 'quick' in the sentence"); } // String equality - the right way String password = "secret123"; String userInput = "secret123"; if (password.equals(userInput)) { // Correct way to compare contents System.out.println("Password correct"); } // Using compareTo for ordering String word1 = "apple"; String word2 = "banana"; int comparison = word1.compareTo(word2); // Negative value if (comparison < 0) { System.out.println(word1 + " comes before " + word2); } } }
A common manipulation pattern using only Quick Reference methods:
</>Javapublic class StringManipulation { // Get the single character at a position as a String public static String getSingleCharAt(String str, int index) { return str.substring(index, index + 1); } // Find the first space and split a name into two parts public static String swapNameOrder(String fullName) { int spaceIndex = fullName.indexOf(" "); if (spaceIndex == -1) { return fullName; // no space, return as is } String first = fullName.substring(0, spaceIndex); String last = fullName.substring(spaceIndex + 1); return last + ", " + first; } }
Note on finding more than one occurrence: the single-argument indexOf(String) always searches from the start, so to find a later occurrence you search a substring of the original and adjust the returned index. For example, after finding the first space, search fullName.substring(spaceIndex + 1) and add spaceIndex + 1 to the result to get the next space's real index.
Common Errors and Debugging
StringIndexOutOfBoundsException
This run-time error occurs when you access a position that does not exist in the String.
</>JavaString text = "Hello"; String sub = text.substring(2, 10); // Error! 10 is beyond the string length
Common causes:
- Off-by-one errors (forgetting indices start at 0)
- Not checking the String length before accessing
- Calling
substringwith an end index greater thanlength()
Prevention:
</>Java// Validate both indices before calling substring if (start >= 0 && end <= text.length() && start <= end) { String sub = text.substring(start, end); }
Using == Instead of equals()
The == operator checks whether two references point to the same object, not whether they hold the same characters. Use equals for content.
</>JavaString s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false - different objects System.out.println(s1.equals(s2)); // true - same content
Rule: use .equals() to compare String contents. Only use == when you specifically need to check whether two variables reference the exact same object.
Forgetting String Immutability
Calling a method without storing the result does nothing useful, because the original String cannot change.
</>JavaString name = "alice"; name.substring(0, 1); // result discarded, name is unchanged System.out.println(name); // still prints "alice" // Correct approach: store the result String firstLetter = name.substring(0, 1);
Think of String methods as producing new Strings based on the original, not as tools that change the existing String.
Off-By-One Errors with substring
The end index of substring is exclusive.
</>JavaString text = "Hello"; // Want characters at positions 1, 2, 3 String sub = text.substring(1, 4); // CORRECT - gets positions 1, 2, 3
Remember: substring(from, to) includes from but excludes to. The number of characters extracted is always to - from.
Practice Problems
Problem 1: Email Parser
Write a method that extracts the username and domain from an email address and returns them in the format "Username: [username], Domain: [domain]".
</>Javapublic static String parseEmail(String email) { // Handle missing @ symbol if (email.indexOf("@") == -1) { return "Invalid email"; } int atIndex = email.indexOf("@"); String username = email.substring(0, atIndex); String domain = email.substring(atIndex + 1); return "Username: " + username + ", Domain: " + domain; } // Test cases: System.out.println(parseEmail("john.doe@example.com")); // Output: "Username: john.doe, Domain: example.com" System.out.println(parseEmail("student123@school.edu")); // Output: "Username: student123, Domain: school.edu"
Problem 2: Password Length and Digit Check
Create a method that checks whether a password is at least 8 characters long and contains at least one digit. You can test each character by pulling it out as a single-character substring and comparing it to "0" and "9".
</>Javapublic static boolean isValidPassword(String password) { if (password.length() < 8) { return false; } for (int i = 0; i < password.length(); i++) { String ch = password.substring(i, i + 1); if (ch.compareTo("0") >= 0 && ch.compareTo("9") <= 0) { return true; // Found a digit } } return false; // No digits found }
Problem 3: Swap First and Last Name
Write a method that takes a name like "john doe" and returns "doe, john". Assume there is exactly one space.
</>Javapublic static String swapName(String fullName) { int spaceIndex = fullName.indexOf(" "); if (spaceIndex == -1) { return fullName; // no space found } String first = fullName.substring(0, spaceIndex); String last = fullName.substring(spaceIndex + 1); return last + ", " + first; } // Test: System.out.println(swapName("john doe")); // "doe, john" System.out.println(swapName("mary smith")); // "smith, mary"
How to Use This on the AP Computer Science A Exam
MCQ
String questions are common in multiple choice. Expect to trace concatenation, predict what substring returns, and figure out what indexOf gives back. Pay close attention to boundary cases: empty Strings, a not-found result of -1, and index calculations. Questions often test immutability by calling a method without storing its result, then asking what the original String contains. The answer is that it is unchanged.
Free Response
Free-response code-writing tasks can require calling String methods inside an algorithm. These problems often combine String methods with loops and conditionals, such as walking through a String one character at a time using substring(i, i + 1), or repeatedly using indexOf to find occurrences. Keep the Java Quick Reference method names and behavior fresh so you call them correctly.
Code Tracing
When tracing, write out the index of each character before you predict a substring result, and remember the end index is excluded. Track every reassignment, since immutability means the value only changes when you assign a method's return value back to a variable.
Common Trap
The biggest trap is assuming a String method changes the original String. It never does. If you call text.substring(0, 3) and do not assign the result, text keeps its old value. A second frequent trap is using == to compare String contents; that compares references, not characters, so use equals for content. Finally, watch the exclusive end index in substring(from, to): the character at to is not part of the result, and the length of the result is always to - from.
Common Misconceptions
- "String methods change the String." They do not. Strings are immutable, so methods return a new String and leave the original unchanged. Always store the return value.
- "
==compares String contents." It compares whether two references point to the same object. Useequalsto compare the actual characters. - "
substring(from, to)includes the character atto." It does not. The result ends at indexto - 1, so it containsto - fromcharacters. - "
indexOfreturns 0 when the text is missing." It returns-1when the search String is not found. A return of 0 means the match starts at the very first index. - "Indices start at 1." String indices start at 0 and end at
length() - 1. Accessing outside that range throws aStringIndexOutOfBoundsException. - "You can use
indexOfwith a starting position to skip ahead." The version ofindexOfcovered here searches from the start of the String. To find a later occurrence, search asubstringand adjust the returned index.
Related AP Computer Science A Guides
Vocabulary
The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.Term | Definition |
|---|---|
compareTo() method | A String method that compares two strings alphabetically and returns a negative value if the first string is less than the second, zero if they are equal, or a positive value if the first string is greater than the second. |
concatenation | The process of combining two or more String objects or a String with a primitive value using the + or += operator to create a new String object. |
equals method | A String method that returns true if the string contains the same sequence of characters as another string, and false otherwise. |
immutable | A property of String objects meaning that once created, their content cannot be changed; methods called on a String return a new String rather than modifying the original. |
implicit conversion | The automatic conversion of a primitive value to a String object when concatenated with a String. |
index | A numeric position in a string, starting from 0 for the first character and going up to one less than the length of the string. |
indexOf() method | A String method that returns the index of the first occurrence of a specified substring, or -1 if the substring is not found. |
java.lang package | A Java package containing fundamental classes that are automatically available without explicit import statements. |
length() method | A String method that returns the number of characters in a String object as an integer. |
method overriding | When a public method in a subclass has the same method signature as a public method in the superclass but with subclass-specific behavior. |
Object class | The superclass in Java from which all classes inherit, guaranteeing the existence of the toString method. |
String class constructor | A method that creates a new String object by calling the String class constructor. |
string literal | A sequence of characters enclosed in double quotes used to create a String object directly in code. |
String object | An instance of the String class in Java that represents a sequence of characters. |
StringIndexOutOfBoundsException | An exception thrown when attempting to access a string index that is outside the valid range of 0 to length - 1. |
substring() method | A String method that returns a portion of a string, either from a starting index to an ending index, or from a starting index to the end of the string. |
toString method | A method that returns a string representation of an object, automatically called when an object is concatenated with a String. |
Frequently Asked Questions
What is a String in Java?
A String in Java is an object that stores a sequence of characters, such as "hello" or "AP CSA". Strings are commonly created with string literals.
What String methods are on the AP CSA Java Quick Reference?
The AP CSA Java Quick Reference includes String methods such as length(), substring(int from, int to), substring(int from), indexOf(String str), equals(Object other), and compareTo(String other).
How does substring work in Java?
substring(from, to) includes the character at from and excludes the character at to. That means the length of the result is to minus from.
Why should I use equals instead of == for Strings?
Use equals to compare String contents. The == operator checks whether two references point to the same object, not whether the characters match.
What does it mean that Strings are immutable?
Immutable means a String object cannot be changed after it is created. String methods return new Strings, so you need to store the return value if you want to use the result.
How are String methods tested on the AP Computer Science A exam?
You may trace code with length, substring, indexOf, equals, compareTo, concatenation, and loops that inspect one character at a time using substring(i, i + 1).