AP Computer Science A – 1.15 String Manipulation

What Is a String?

In Java, a String is an object used to store and work with text.

String name = "Jordan";
String school = "Klein Collins";
String message = "Hello, world!";

The String class contains many built-in instance methods that allow you to:

These skills are used constantly in real programs, such as:


1. substring() – Extract Part of a String

The substring() method is used to cut out a portion of a string.

Format:

string.substring(startIndex, endIndex)

Example 1:

String word = "Computer";
System.out.println(word.substring(0, 3));

Output:

Com

Example 2:

System.out.println(word.substring(4));

Output:

uter

Common uses:


2. indexOf() – Find the Position of a Character or Word

The indexOf() method finds the location of a character or substring in a string.

Format:

string.indexOf("text")

Example:

String word = "Programming";
System.out.println(word.indexOf("g"));

Possible Output:

3

If the value is not found, the result is:

-1

Common uses:


3. equals() – Compare Two Strings for Equality

The equals() method checks if two Strings have the exact same value.

Important: Never use == to compare Strings in Java.

Correct Way:

String a = "Java";
String b = "Java";

System.out.println(a.equals(b));

Output:

true

If they are different, the result is:

false

4. compareTo() – Alphabetical Comparison

The compareTo() method compares two Strings alphabetically.

Format:

string1.compareTo(string2)

Results:

Result Meaning
0 Strings are equal
Negative number string1 comes before string2
Positive number string1 comes after string2

Example:

System.out.println("Apple".compareTo("Banana"));

Output: a negative number (because "Apple" comes before "Banana")

Common uses:


Common String Methods to Know

Method Purpose
.length() Returns the number of characters in the String
.substring() Extracts part of a String
.indexOf() Finds the position of a character or substring
.equals() Compares two Strings for exact equality
.compareTo() Compares two Strings alphabetically
.toUpperCase() Converts all letters to uppercase
.toLowerCase() Converts all letters to lowercase

Why String Manipulation Matters in APCS A

In AP Computer Science A, you will use String manipulation to:


AP Exam Tips