![]() |
VOOZH | about |
The String lastIndexOf() method returns the position of the last occurrence of a given character or substring in a String. The Index starts from 0, and if the given substring is not found it returns -1.
In this article, we will learn how to use the string lastIndexOf() method in Java to find the last occurrence of a character or substring in a String.
This program demonstrates how to use the lastIndexOf() method to find the position of the last occurrence of a specified character in a given string.
Found Last Index of l at: 9
Table of Content
There are four variants of the lastIndexOf() method in Java.
| Method | Description |
|---|---|
| int lastIndexOf(char ch) | It returns the index of the last occurrence of the specified character. |
| public int lastIndexOf(char ch, int fromIndex) | It returns the index of the last occurrence of the specified character, searching backward starting at the specified index. |
| public int lastIndexOf(String str) | It returns the index of the last occurrence of the specified substring. |
| public int lastIndexOf(String str, int fromIndex) | It returns the index of the last occurrence of the specified substring, searching backward starting at the specified index. |
Parameters:
Return Value:
Now, lets see examples of all 4 variants of lastIndexOf() method of String class.
To demonstrate how to find the last index of a character in a string.
Last index of 'G': 8
To illustrate the last index of 'g' in a specific string.
Found Last Index of g at: 19
To show how to find the last index of a character, searching backwards from a specified index.
Found Last Index of g at: 11
To demonstrate how to find the last index of a substring in a string.
Found substring geeks at: 19
To show how to find the last index of a substring, searching backwards from a specified index.
Found substring geeks at: 11