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:
substring() – Extract Part of a String
The substring() method is used to cut out a portion of a string.
string.substring(startIndex, endIndex)
startIndex is includedendIndex is not includedString word = "Computer";
System.out.println(word.substring(0, 3));
Output:
Com
System.out.println(word.substring(4));
Output:
uter
Common uses:
indexOf() – Find the Position of a Character or Word
The indexOf() method finds the location of a character or substring in a string.
string.indexOf("text")
String word = "Programming";
System.out.println(word.indexOf("g"));
Possible Output:
3
If the value is not found, the result is:
-1
Common uses:
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.
String a = "Java";
String b = "Java";
System.out.println(a.equals(b));
Output:
true
If they are different, the result is:
false
compareTo() – Alphabetical Comparison
The compareTo() method compares two Strings alphabetically.
string1.compareTo(string2)
| Result | Meaning |
|---|---|
0 |
Strings are equal |
| Negative number | string1 comes before string2 |
| Positive number | string1 comes after string2 |
System.out.println("Apple".compareTo("Banana"));
Output: a negative number (because "Apple" comes before "Banana")
Common uses:
| 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 |
In AP Computer Science A, you will use String manipulation to:
substring() works (start included, end excluded).== does not compare String contents.equals() to compare the value of Strings.compareTo() mean (0, negative, positive).