Java String Methods Notes: substring() and indexOf()

Big Idea

In Java, a String is a sequence of characters. Each character has a position number called an index.

Important: Indexes start at 0, not 1.
String word = "computer";
Index 01234567
Char computer

1️⃣ indexOf() Method

Purpose

indexOf() finds the position (index) of a character or substring inside a String.

Syntax

stringName.indexOf(value)

Examples

String word = "computer";

int pos1 = word.indexOf("c");   // 0
int pos2 = word.indexOf("p");   // 3
int pos3 = word.indexOf("er");  // 6

If the value is NOT found

int pos = word.indexOf("z");  // -1
If indexOf() returns -1, the character or substring does not exist in the String.

2️⃣ substring() Method

Purpose

substring() extracts part of a String.

Two Versions of substring()

Version 1: Start Index Only

stringName.substring(startIndex)

This returns everything from the start index to the end of the String.

String word = "computer";
String part = word.substring(3);
System.out.println(part);
Output: puter

Version 2: Start and End Index

stringName.substring(startIndex, endIndex)
String word = "computer";
String part = word.substring(1, 4);
System.out.println(part);
Output: omp

Indexes used: start at index 1 (o) and stop before index 4.

3️⃣ substring() Visual Example

String text = "JavaProgramming";
Index 01234567
Char JavaProg
text.substring(0, 4);  // "Java"
text.substring(4, 11); // "Program"

4️⃣ Using indexOf() with substring()

These methods are often used together.

Example: Extract a Username

String email = "student@school.com";

int atIndex = email.indexOf("@");
String username = email.substring(0, atIndex);

System.out.println(username);
Output: student

5️⃣ Common Mistakes (AP Exam Warning ⚠️)

❌ Off-by-One Error

word.substring(1, 3);

This gives characters at index 1 and 2 (end index not included).

❌ Assuming indexOf() Always Finds Something

int pos = word.indexOf("z"); // -1
word.substring(pos);         // ERROR

✅ Always check first:

if (pos != -1) {
    // safe to use pos
}

❌ Confusing Length with Index

word.substring(0, word.length());     // entire string
word.substring(0, word.length() - 1); // removes last character

6️⃣ Quick Practice

Given:

String msg = "HelloWorld";
  1. What does this return?
    msg.indexOf("W");
  2. What does this return?
    msg.substring(5);
  3. What does this return?
    msg.substring(0, 5);

7️⃣ Summary Cheat Sheet

Method Purpose
indexOf() Finds the position of a character or substring
substring(start) Gets text from start index to the end
substring(start, end) Gets text between indexes (end not included)
Indexes Start at 0
End index Not included