Java String - lastIndexOf() Method
The Java lastIndexOf() method is used to find out the index number for last occurrence of specified character or substring in the given string or specified substring of the given string ending at the specified index.
Syntax
public int lastIndexOf(int ch) public int lastIndexOf(int ch, int fromIndex) public int lastIndexOf(String str) public int lastIndexOf(String str, int fromIndex)
Parameters
ch |
specify the character to search for. |
str |
specify the substring to search for. |
fromIndex |
specify the index from which to start the search in backward direction. |
Return Value
Returns the index number for last occurrence of specified character or string. Returns -1 if there is no such occurrence.
Exception
NA.
Example:
In the example below, lastIndexOf() method is used to find out the index number for last occurrence of specified character in the given string.
public class MyClass { public static void main(String[] args) { String MyString = "Java is a programming language. Learning Java is fun."; //index number of last occurrence //of 'J' in the given string System.out.println(MyString.lastIndexOf('J')); //index number of last occurrence //of 'J' in the given substring System.out.println(MyString.lastIndexOf('J', 20)); } }
The output of the above code will be:
41 0
Example:
Here, the lastIndexOf() method is used to find out the index number for last occurrence of specified substring in the given string.
public class MyClass { public static void main(String[] args) { String MyString = "Java is a programming language. Learning Java is fun."; //index number of last occurrence //of "is" in the given string System.out.println(MyString.lastIndexOf("is")); //index number of last occurrence //of "is" in the given substring System.out.println(MyString.lastIndexOf("is", 20)); } }
The output of the above code will be:
46 5
❮ Java String Methods