scoresvideos
AP Computer Science A
One-page, printable cheatsheet
Cheatsheet visualization
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

2.7 String Methods

Verified for the 2025 AP Computer Science A examCitation:

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.

Important Terms to Know

  • CompareTo(String other): used to compare two strings lexicographically. It returns an integer value that indicates the relationship between the two strings.
  • Substring: extracting a smaller part of a larger string by specifying its starting and ending positions.
  • IndexOf(string str): used to find the index position of the first occurrence of a specified substring within a larger string.

What is the String Class?

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:

  • Strings are objects, not primitive types like int or double
  • Strings are immutable (cannot be changed after creation)
  • String objects have index values ranging from 0 to length-1
  • Attempting to access indices outside this range will result in an IndexOutOfBoundsException

Creating String Objects

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"

Common String Methods

The String class includes many useful methods. Here are some of the most frequently used:

MethodDescriptionExampleResult
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

String Indexing and Substrings

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"
    

String Concatenation

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."

String Comparison

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");
}

Practical Examples

Example 1: Counting characters in a String

String text = "Hello, World!";
int length = text.length();
System.out.println("The string has " + length + " characters.");

Example 2: Finding a substring

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");
}

Example 3: Processing each character

String code = "Java";
for (int i = 0; i < code.length(); i++) {
    System.out.println("Character at position " + i + ": " + code.charAt(i));
}

Example 4: Extracting parts of an email address

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);
}

Additional String Methods

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

Common Pitfalls and Tips

  1. 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
    
  2. Efficiency: For heavy string manipulation, consider using StringBuilder instead of multiple concatenations with +.

  3. Null Strings: Always check if a string is null before calling methods on it.

    if (str != null && str.length() > 0) {
        // Safe to process str
    }
    
  4. Case Sensitivity: String comparisons are case-sensitive. Use equalsIgnoreCase() for case-insensitive comparisons.

  5. 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.

Key Terms to Review (9)

CompareTo(String other): The compareTo method is used to compare two strings lexicographically. It returns an integer value that indicates the relationship between the two strings.
External Libraries: External libraries are pre-written code that can be imported into a program to provide additional functionality. They contain a collection of classes and methods that can be used to perform specific tasks without having to write the code from scratch.
IndexOf(String str): The indexOf(String str) method is used to find the index position of the first occurrence of a specified substring within a larger string.
Inheritance: Inheritance is a concept in object-oriented programming where a class inherits the properties and behaviors of another class. It allows for code reuse and promotes the creation of hierarchical relationships between classes.
Length() method: The length() method is a built-in function in Java that returns the number of characters in a string.
Overloaded Methods: Overloaded methods are multiple methods in a class with the same name but different parameters. They allow you to perform similar operations on different types of data.
String class: The String class is a built-in class in Java that represents a sequence of characters. It provides various methods to manipulate and work with strings.
Substring: A substring refers to extracting a smaller part of a larger string by specifying its starting and ending positions.
Zero-indexed language: In computer programming, zero-indexed language refers to systems where counting starts from 0 instead of 1 when accessing elements in an ordered collection (e.g., arrays).