Java String - indexOf() Method
The java.lang.String.indexOf() method is used to find out the index number for first occurrence of specified substring in the given string.
Syntax
public int indexOf(String str)
Parameters
str |
specify the substring to search for. |
Return Value
Returns the index number for first occurrence of specified substring. Returns -1 if there is no such occurrence.
Exception
NA.
Example:
Here, the indexOf() method is used to find out the index number for first occurrence of specified substring in the given string.
import java.lang.*; public class MyClass { public static void main(String[] args) { String MyString = "Java is a programming language. Learning Java is fun."; //index number of first occurrence //of "is" in the given string System.out.println(MyString.indexOf("is")); } }
The output of the above code will be:
5
❮ Java.lang - String