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
Syntax
string.indexOf(str, fromIndex)
Parameters
| Parameter | Description |
|---|---|
strString / char |
The character or text to find. |
fromIndex optionalint |
Where to start searching. Default: 0 |
Return value
An int index or -1.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
string.contains()· Return true if the string contains a sequence of characters. Case-sensitive.string.substring()· Return part of a string from a start index up to (not including) an end index. The original is unchanged.- Java Strings · tutorial