The String.indexOf() method searches a string from left to right and returns the zero-based index of the first occurrence of a specified character or substring, returning -1 if not found.
Forward Searching & Substring Navigation: To search backward from the end of a string, explore lastIndexOf(). To extract characters by index position, see charAt(). For substring slicing, explore substring(). For boolean presence checks, see contains(), or measure length with length().
Java provides four overloads in java.lang.String to support character and substring searches with optional start positions:
// 4 Overloaded signatures of indexOf() in java.lang.String
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
| Signature | Search Target | Start Offset Behavior |
|---|---|---|
indexOf(int ch) |
Single character (or Unicode code point) | Starts searching from beginning index 0. |
indexOf(int ch, int fromIndex) |
Single character | Starts searching at index fromIndex forward. |
indexOf(String str) |
Substring text sequence | Starts searching from beginning index 0. |
indexOf(String str, int fromIndex) |
Substring text sequence | Starts searching at index fromIndex forward. |
When searching for a character, Java scans from index 0 and returns the first matching index. If missing, it returns -1:
String str = "Welcome to plus2net.com";
System.out.println("First 'e': " + str.indexOf('e')); // 1
System.out.println("First '2': " + str.indexOf('2')); // 15
System.out.println("Missing 'z': " + str.indexOf('z')); // -1Terminal Output:
First 'e': 1
First '2': 15
Missing 'z': -1
By supplying a fromIndex parameter, you skip earlier matches to locate repeated occurrences of a character:
String str = "Welcome to plus2net.com";
System.out.println("Search from index 0: " + str.indexOf('e', 0)); // 1
System.out.println("Search from index 2: " + str.indexOf('e', 2)); // 6
System.out.println("Search from index 7: " + str.indexOf('e', 7)); // 19Terminal Output:
Search from index 0: 1
Search from index 2: 6
Search from index 7: 19
When you pass a String argument, indexOf() locates the starting index of the full substring sequence:
String text = "Welcome to plus2net.com";
System.out.println("Position of 'co': " + text.indexOf("co")); // 3 (in 'Welcome')
System.out.println("Position of 'plus': " + text.indexOf("plus")); // 11
System.out.println("Position of 'java': " + text.indexOf("java")); // -1Terminal Output:
Position of 'co': 3
Position of 'plus': 11
Position of 'java': -1
Combining substring search with fromIndex allows stepping over earlier words to find subsequent occurrences:
String text = "Welcome to plus2net.com";
System.out.println("First 'co': " + text.indexOf("co")); // 3
System.out.println("'co' starting from 4: " + text.indexOf("co", 4)); // 20 (in '.com')
System.out.println("'com' starting from 4: " + text.indexOf("com", 4)); // 20Terminal Output:
First 'co': 3
'co' starting from 4: 20
'com' starting from 4: 20
While indexOf() scans left-to-right from the beginning, lastIndexOf() scans right-to-left from the end:
| Feature | str.indexOf(...) |
str.lastIndexOf(...) |
|---|---|---|
| Search Direction | Forward (Left to Right). | Backward (Right to Left). |
| Default Offset | Starts at index 0. |
Starts at str.length() - 1. |
| Returned Position | Index of the first occurrence. | Index of the last occurrence. |
String sentence = "Java is powerful and Java is fast";
// indexOf() searches from left to right
System.out.println("First 'Java': " + sentence.indexOf("Java")); // 0
// lastIndexOf() searches from right to left
System.out.println("Last 'Java': " + sentence.lastIndexOf("Java")); // 20Terminal Output:
First 'Java': 0
Last 'Java': 20
To locate every occurrence of a word throughout a document, advance fromIndex on each iteration inside a while loop:
String content = "cat bat cat rat cat";
String target = "cat";
int count = 0, index = 0;
while ((index = content.indexOf(target, index)) != -1) {
System.out.println("Found at index: " + index);
count++;
index += target.length(); // Advance past match
}
System.out.println("Total: " + count);Terminal Output:
Found at index: 0
Found at index: 8
Found at index: 16
Total: 3
A classic real-world application of indexOf() is combining delimiter searches with substring() to split structured text:
String email = "support@plus2net.com";
int atIndex = email.indexOf('@');
int dotIndex = email.indexOf('.', atIndex);
if (atIndex != -1 && dotIndex != -1) {
System.out.println("Username: " + email.substring(0, atIndex));
System.out.println("Domain: " + email.substring(atIndex + 1));
}Terminal Output:
Username: support
Domain: plus2net.com
Never write if (str.indexOf("target") > 0). If the match occurs at the very start of the string (index 0), this condition evaluates to false! Always check != -1.
When searching inside a while loop, you must increment the offset past the match: index = pos + target.length(). Re-searching from pos causes an infinite loop on the same match.
You can compile and run this complete verification class locally in any Java development environment:
public class StringIndexOfFullDemo {
public static void main(String[] args) {
String data = "user:admin@plus2net.com";
// 1. Locate delimiter ':'
int colon = data.indexOf(':');
if (colon == 4) {
System.out.println("Check 1 Passed: Colon found at index 4.");
}
// 2. Locate '@' starting from colon position
int atSign = data.indexOf('@', colon);
if (atSign == 10) {
System.out.println("Check 2 Passed: At-sign found at index 10.");
}
// 3. Confirm missing search returns -1
int missing = data.indexOf("guest");
if (missing == -1) {
System.out.println("Check 3 Passed: Missing term returned -1.");
}
System.out.println("All String.indexOf() tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Colon found at index 4.
Check 2 Passed: At-sign found at index 10.
Check 3 Passed: Missing term returned -1.
All String.indexOf() tests passed successfully!
If fromIndex < 0, Java treats it as 0 and searches the entire string from the beginning without throwing an exception.
If fromIndex >= length(), indexOf() returns -1, except when searching for the empty string "", which returns length().
Yes. "hello".indexOf("H") returns -1. To perform a case-insensitive search, normalize both strings with toLowerCase() first.
Searching for an empty string "" returns 0 (or fromIndex if specified, up to length()).
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.