In Java, indexOf() searches a string from left to right and returns the zero-based position where a character or a piece of text first appears. If it never appears, the result is -1.
Use it to locate a separator such as '@' or ':', to test whether something is present and where, or to walk through every occurrence with the fromIndex overload. The search is case-sensitive: "Na" is not found in "banana".
indexOf() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.indexOf(...); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed.
Syntax
Pass a char or a String, optionally with the index where the search should start.
java
int at = email.indexOf('@'); // first '@'
int word = text.indexOf("Java"); // first "Java"
int next = text.indexOf("Java", at + 1); // search again after a hit
Call
What it does
"banana".indexOf('n')
Returns 2, the first 'n'.
"banana".indexOf("an", 2)
Starts looking at index 2 and returns 3.
"banana".indexOf("x")
Returns -1: not found.
"banana".indexOf("")
Returns 0: the empty string is found at the start.
The int ch overloads accept a char (it widens to int) or a full Unicode code point, so they can find emoji too. A fromIndex below 0 is treated as 0, and one past the end simply returns -1; these overloads never throw for a bad index.
Library declarations
java
public int indexOf(int ch);
public int indexOf(int ch, int fromIndex);
public int indexOf(String str);
public int indexOf(String str, int fromIndex);
// Java 21+
public int indexOf(int ch, int beginIndex, int endIndex);
public int indexOf(String str, int beginIndex, int endIndex);
Parameters
Parameter
Description
ch
The character (or code point) to look for.
str
The substring to look for. Must not be null.
fromIndex
Optional. Where the search starts. Defaults to 0.
beginIndex, endIndex
Java 21+ only. Search only inside [beginIndex, endIndex).
Return Value
Return Value
Description
int
The index of the first match at or after the start position.
-1
When there is no match.
Java Examples
Example 1 — Find a Character and a Substring
Look up a char, a two-letter substring, a wrong-case substring, and a missing letter in "banana".
java
public class IndexOfBasics {
public static void main(String[] args) {
String fruit = "banana";
System.out.println("indexOf('a') = " + fruit.indexOf('a'));
System.out.println("indexOf(\"na\") = " + fruit.indexOf("na"));
System.out.println("indexOf(\"Na\") = " + fruit.indexOf("Na"));
System.out.println("indexOf('z') = " + fruit.indexOf('z'));
}
}
First hit wins."banana" has 'a' at 1, 3, and 5; indexOf stops at the leftmost one and returns 1.
Substrings report their start."na" occupies indexes 2 and 3, so the answer is 2, the position of its first letter.
Exact case, or -1. Capital "Na" and the absent 'z' both return -1: the method never guesses or ignores case.
Example 2 — Count Every Occurrence with fromIndex
Restart the search just after each hit to list all positions of "be" in a famous line.
java
public class IndexOfCountAll {
public static void main(String[] args) {
String text = "to be or not to be";
int count = 0;
int pos = text.indexOf("be");
while (pos != -1) {
System.out.println("Found at " + pos);
count++;
pos = text.indexOf("be", pos + 1);
}
System.out.println("Total: " + count);
}
}
Output
Found at 3
Found at 16
Total: 2
How It Works
Prime the loop. The first call finds "be" at index 3 (after "to ").
Search past the last hit.indexOf("be", pos + 1) begins at index 4, skips ahead, and finds the second "be" at 16.
-1 ends the loop. Searching from 17 finds nothing, the method returns -1, and the counter stops at 2.
Example 3 — Split an Email Address at the @ Sign
Combine indexOf with substring, and handle input that has no @ at all.
java
public class IndexOfEmail {
public static void main(String[] args) {
String[] inputs = {"[email protected]", "no-at-sign"};
for (String email : inputs) {
int at = email.indexOf('@');
if (at == -1) {
System.out.println(email + " -> no @ found");
} else {
String user = email.substring(0, at);
String domain = email.substring(at + 1);
System.out.println(email + " -> user=" + user + ", domain=" + domain);
}
}
}
}
Output
[email protected] -> user=ada, domain=example.com
no-at-sign -> no @ found
How It Works
Locate the separator. In "[email protected]" the '@' sits at index 3.
Cut on both sides.substring(0, 3) gives "ada" and substring(4) gives "example.com"; the original email string is not modified.
Guard against -1."no-at-sign" returns -1, so the code prints a message instead of calling substring(0, -1), which would throw.
Frequently Asked Questions
It returns the zero-based index of the first occurrence of a char or substring, or -1 if it does not occur.
Yes. "banana".indexOf("Na") is -1. Convert both strings with toLowerCase(Locale.ROOT) first if you need a case-insensitive search.
Call indexOf once, then keep calling indexOf(str, previous + 1) until it returns -1, counting or printing each position.
contains() only answers yes or no. indexOf() tells you where the text starts, and returns -1 when it is missing. contains(s) is the same as indexOf(s) >= 0.
No. A negative fromIndex is treated as 0 and a fromIndex past the end returns -1. Only a null search string (NullPointerException) or the Java 21 range overloads with an invalid range throw.