indexOf(String str)
Returns the index of the first occurrence of the specified substring within this string.
Syntax:
public int indexOf(String str)
Note: If no such occurrence of a substring within this string then it returns -1.
lastIndexOf(String str)
Returns the index of the last occurrence of the specified substring within this string.
Syntax:
public int lastIndexOf(String str)
Note: If no such occurrence of a substring within this string then it returns -1.
Example:
class TestString{ String str = "www.w3schools.blog"; public void indexOfTest(){ System.out.println(str.indexOf("o")); } public void lastIndexOfTest(){ System.out.println(str.lastIndexOf("o")); } } public class StringIndexTestExample { public static void main(String args[]){ //creating TestString object TestString obj = new TestString(); //method call obj.indexOfTest(); obj.lastIndexOfTest(); } }
Output
9 18