01 / 21
"Str" ( )

Java String Methods

Master the essential String methods: substring, indexOf, equals, and compareTo to manipulate and compare text in Java.

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.

String greeting = "Hello, World!";

The Index Model

Each character in a String has a numeric index starting at 0. The last character is at index \(\text{length()} - 1\).

H
e
l
l
o
0
1
2
3
4
Indices for "Hello"

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.

substring
Extract a portion of text from a String
indexOf
Find where a character or substring lives
equals
Check if two Strings have the same content
compareTo
Determine lexicographic order of Strings

The substring Method

substring extracts a portion of a String. It has two forms:

// Form 1: from beginIndex to end str.substring(beginIndex) // Form 2: from beginIndex up to (not including) endIndex str.substring(beginIndex, endIndex)

substring in Action

String s = "Hamburger"; s.substring(4, 8); // returns "urge" s.substring(4); // returns "urger"
H
a
m
b
u
r
g
e
r
0
1
2
3
4
5
6
7
8
begin=4 (inclusive) to end=8 (exclusive) → "urge"

The indexOf Method

indexOf searches for a character or substring and returns the index of its first occurrence. If not found, it returns -1.

String s = "banana"; s.indexOf("an"); // returns 1 s.indexOf("z"); // returns -1 (not found)
b
a
n
a
n
a
0
1
2
3
4
5
First "an" found at index 1

The equals Method

equals compares the content of two Strings and returns true or false. It is case-sensitive.

String a = "Hello"; String b = "Hello"; String c = "hello"; a.equals(b); // true a.equals(c); // false (case differs)

The compareTo Method

compareTo compares two Strings in lexicographic (dictionary) order and returns an integer:

Negative
Calling String comes before the argument alphabetically
Zero
Both Strings are equal
Positive
Calling String comes after the argument alphabetically
"apple".compareTo("banana"); // negative (a < b) "cat".compareTo("cat"); // 0 (equal) "dog".compareTo("cat"); // positive (d > c)

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

1
Identify the task: Are you searching, extracting, or comparing?
2
Choose the right method: indexOf for searching, substring for extracting, equals/compareTo for comparing.
3
Count indices carefully: Remember zero-based indexing. Draw out the index boxes if needed.
4
Check boundaries: substring's endIndex is exclusive. indexOf returns \(-1\) if not found.
5
Store or use the result: String methods return values: assign to a variable or use in a condition.

Example 1: Extract a Domain

Given an email address, extract just the domain name:

String email = "student@school.edu"; int atPos = email.indexOf("@"); // 7 String domain = email.substring(atPos + 1); // "school.edu"
s
t
u
d
e
n
t
@
s
c
h
o
o
l
.
e
d
u
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ at index 7 → substring from 8 to end
Result: "school.edu"

Example 2: Validate Input

Check if a user typed "yes" regardless of case:

String input = "YES"; // Wrong: case-sensitive comparison input.equals("yes"); // false! // Correct: case-insensitive comparison input.equalsIgnoreCase("yes"); // true

Example 3: Sorting Names

Use compareTo to decide the alphabetical order of two names:

String name1 = "Maria"; String name2 = "James"; int result = name1.compareTo(name2); // result is positive (M comes after J) if (result < 0) { // name1 comes first } else if (result > 0) { // name2 comes first } else { // names are equal }

Common Mistakes

✕ Using \(==\) for Strings
Using \(==\) compares object references, not content. Always use .equals() for String comparison.
✕ Off-by-one in substring
Forgetting that the endIndex is exclusive. substring(2, 5) gives characters at indices 2, 3, 4: not 5.
✕ Ignoring -1 from indexOf
Not checking if indexOf returns \(-1\) before using the result in substring causes a StringIndexOutOfBoundsException.
✕ Case sensitivity
Forgetting that "Hello".equals("hello") is false. Use equalsIgnoreCase() when case does not matter.

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?