Java 25 (LTS) reference · String Methods

Java String indexOf() Method

Return the index of the first occurrence of a character or substring, or -1 if it isn't found.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.indexOf(str, fromIndex)

Parameters

ParameterDescription
str
String / char
The character or text to find.
fromIndex optional
int
Where to start searching. Default: 0

Return value

An int index or -1.

Examples

First, next and last match
public class Main {
    public static void main(String[] args) {
        String s = "banana";
        System.out.println(s.indexOf("an"));
        System.out.println(s.indexOf("an", 2));
        System.out.println(s.lastIndexOf("an"));
        System.out.println(s.indexOf("x"));
    }
}

Output

1
3
3
-1

Run this on your computer — see “Get Started” for setup.

Check for -1
public class Main {
    public static void main(String[] args) {
        String url = "https://readycamel.com/tutorials?lang=java";
        int q = url.indexOf("?");
        System.out.println(q == -1 ? "no query" : url.substring(q + 1));
    }
}

Output

lang=java

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?