Java String Methods
Master the essential String methods: substring, indexOf, equals, and compareTo to manipulate and compare text in Java.
What Is a String?
A String in Java is a sequence of characters enclosed in double quotes. Strings are objects, not primitives, which means they come with a rich set of built-in methods you can call.
The Index Model
Each character in a String has a numeric index starting at 0. The last character is at index \(\text{length()} - 1\).
Why String Methods Matter
Almost every Java program handles text: user input, file data, web content. Knowing these four core methods gives you power to search, extract, and compare text efficiently.
The substring Method
substring extracts a portion of a String. It has two forms:
substring in Action
The indexOf Method
indexOf searches for a character or substring and returns the index of its first occurrence. If not found, it returns -1.
The equals Method
equals compares the content of two Strings and returns true or false. It is case-sensitive.
The compareTo Method
compareTo compares two Strings in lexicographic (dictionary) order and returns an integer:
equals() vs \(==\)
This is the most critical distinction for Java String comparison. Understanding the difference prevents one of the most common bugs.
| .equals() | \(==\) | |
|---|---|---|
| Compares | Character content | Object reference (memory address) |
| Returns | true if same characters | true only if same object |
| Use for | Almost always | Rarely (checking null) |
| Example | str.equals("Hi") | str \(==\) null |
How to Apply String Methods
Example 1: Extract a Domain
Given an email address, extract just the domain name:
Example 2: Validate Input
Check if a user typed "yes" regardless of case:
Example 3: Sorting Names
Use compareTo to decide the alphabetical order of two names:
Common Mistakes
Method Summary
| Method | Returns | Purpose |
|---|---|---|
| substring(b, e) | String | Extract characters from index b up to (not including) e |
| indexOf(str) | int | Find first occurrence; -1 if not found |
| equals(str) | boolean | Content equality check (case-sensitive) |
| compareTo(str) | int | Lexicographic order: negative, zero, or positive |
Question 1 of 5
What does "computer".substring(3, 6) return?
Question 2 of 5
What does "pineapple".indexOf("app") return?
Question 3 of 5
Which expression correctly checks if two String variables s1 and s2 have the same content?
Question 4 of 5
If "apple".compareTo("cherry") is evaluated, the result will be:
Question 5 of 5
Given String s = "Java";, what does s.indexOf("x") return?