Course contentsShow
← Java
Lesson 2200 of 2,87043. String Handling in DepthFree lesson

Handling indexOf Return Value: -1 for Not Found

Understand that indexOf returns -1 when the search target is not found and how to handle this case.

Handling indexOf Return Value: -1 for Not Found

You'll learn how to properly handle the special return value when indexOf can't find what you're looking for.

The -1 Sentinel Value

When indexOf searches for a character or substring and doesn't find it, it returns -1. This is a sentinel value — a special indicator that means "not found." Since valid string indices start at 0, -1 is safely outside the range and signals failure.

Think of it like asking someone "Which page is the recipe on?" If they say "Page 5," you know where to look. If they say "-1," you know it's not in the book at all.

Why This Matters

If you don't check for -1, you might accidentally use it as if it were a valid index, leading to logic errors. For example, assuming a substring exists when it doesn't could cause incorrect slicing or infinite loops.

Handling the -1 Case

Always check the return value before using it:

String email = "user@example.com";
int atPosition = email.indexOf("@");

if (atPosition == -1) {
    System.out.println("Invalid email: missing @ symbol");
} else {
    System.out.println("@ found at position: " + atPosition);
    String domain = email.substring(atPosition + 1);
    System.out.println("Domain: " + domain);
}

When searching for something that might not exist:

String text = "Hello World";
int pos = text.indexOf("Java");

if (pos != -1) {
    System.out.println("Found Java at: " + pos);
} else {
    System.out.println("Java not found in text");
}
// Output: Java not found in text

Key Takeaway: Always check if indexOf returns -1 before using the result as an index; -1 means the search target was not found and should be handled as a special case.