Verified for the 2025 AP Computer Science A exam•Citation:
In Java programming, the String
class is one of the most commonly used and powerful tools available to developers. Strings allow us to work with text data, and the Java language provides an extensive set of methods to manipulate and analyze this text. Understanding how to use String objects and their methods effectively is crucial for solving a wide range of programming problems, from basic text processing to complex data manipulation.
The String
class is part of the java.lang
package, which is available by default in all Java programs. A String object represents a sequence of characters and provides methods to examine and modify those characters.
Key characteristics of Strings in Java:
int
or double
length-1
IndexOutOfBoundsException
There are several ways to create String objects:
// Using string literals String greeting = "Hello"; // Using the String constructor String name = new String("World"); // Creating an empty string String empty = ""; // String concatenation using the + operator String message = greeting + " " + name; // "Hello World"
The String class includes many useful methods. Here are some of the most frequently used:
Method | Description | Example | Result |
---|---|---|---|
length() | Returns the number of characters | "Java".length() | 4 |
substring(int from, int to) | Returns the substring from index from to index to-1 | "Computer".substring(0, 4) | "Comp" |
substring(int from) | Returns the substring from index from to the end | "Science".substring(3) | "ence" |
indexOf(String str) | Returns the index of the first occurrence of str , or -1 if not found | "Programming".indexOf("gram") | 3 |
equals(String other) | Returns true if this string equals other , false otherwise | "Java".equals("java") | false |
compareTo(String other) | Returns negative if less than, zero if equal, positive if greater than | "Apple".compareTo("Banana") | negative value |
Strings in Java use zero-based indexing:
String s = "Computer"; Indices: 0 1 2 3 4 5 6 7 Characters: C o m p u t e r
To get a single character, use the charAt(int index)
method:
char firstLetter = "Hello".charAt(0); // 'H'
To extract a substring, use one of the substring
methods:
String word = "Computer"; String part1 = word.substring(0, 4); // "Comp" String part2 = word.substring(4); // "uter"
To get a single character as a String:
String letter = "Hello".substring(1, 2); // "e" // Or alternatively: String letter = "Hello".substring(1, 1 + 1); // "e"
Strings can be concatenated (joined together) using the +
operator:
String firstName = "John"; String lastName = "Doe"; String fullName = firstName + " " + lastName; // "John Doe"
When a String is concatenated with an object, the object's toString()
method is implicitly called:
int age = 25; String message = "I am " + age + " years old."; // "I am 25 years old."
To compare strings for equality, use the equals()
method, not the ==
operator:
// Correct way to compare strings if (str1.equals(str2)) { System.out.println("The strings are equal."); } // Incorrect way (checks if they are the same object, not if they have the same content) if (str1 == str2) { // This might not work as expected }
To compare strings lexicographically (alphabetical order), use the compareTo()
method:
String word1 = "apple"; String word2 = "banana"; int result = word1.compareTo(word2); if (result < 0) { System.out.println("apple comes before banana alphabetically"); } else if (result > 0) { System.out.println("apple comes after banana alphabetically"); } else { System.out.println("The words are identical"); }
String text = "Hello, World!"; int length = text.length(); System.out.println("The string has " + length + " characters.");
String sentence = "The quick brown fox jumps over the lazy dog"; int position = sentence.indexOf("fox"); if (position != -1) { System.out.println("Found 'fox' at position " + position); } else { System.out.println("'fox' not found"); }
String code = "Java"; for (int i = 0; i < code.length(); i++) { System.out.println("Character at position " + i + ": " + code.charAt(i)); }
String email = "student@school.edu"; int atSign = email.indexOf("@"); if (atSign != -1) { String username = email.substring(0, atSign); String domain = email.substring(atSign + 1); System.out.println("Username: " + username); System.out.println("Domain: " + domain); }
Beyond the core methods covered above, the String class offers many more useful methods:
toUpperCase()
/ toLowerCase()
- Convert to upper/lower case
trim()
- Remove whitespace from both ends
startsWith(String prefix)
/ endsWith(String suffix)
- Check if string starts/ends with given text
replace(char old, char new)
- Replace all occurrences of a character
contains(String str)
- Check if string contains a substring
split(String regex)
- Split the string into an array based on a delimiter
Immutability: Remember that Strings are immutable. Methods like substring()
don't modify the original string but return a new one.
String word = "Hello"; word.toUpperCase(); // This doesn't change 'word' System.out.println(word); // Still prints "Hello" // Correct usage: word = word.toUpperCase(); // Assigns the new string back to the variable
Efficiency: For heavy string manipulation, consider using StringBuilder
instead of multiple concatenations with +
.
Null Strings: Always check if a string is null before calling methods on it.
if (str != null && str.length() > 0) { // Safe to process str }
Case Sensitivity: String comparisons are case-sensitive. Use equalsIgnoreCase()
for case-insensitive comparisons.
Bounds Checking: Always ensure indices are within the valid range to avoid IndexOutOfBoundsException
.
The String class is a powerful tool in Java programming. By mastering its methods, you'll be able to handle text processing tasks efficiently and solve a wide range of programming problems. The methods mentioned in this guide are essential knowledge for the AP Computer Science A exam and will serve as building blocks for more complex programming tasks.