If you want to know the last index position of a substring or a character in a string, then use the lastIndexOf() method in Java. It returns the index position, but if the substring or a character is not available in a string, the method will return -1.
Method signature:
The signature for a lastIndexOf() method is as shown below.
- int lastIndexOf(int index)
- int lastIndexOf(int index, int startIndex)
- int lastIndexOf(String substring)
- int lastIndexOf(String substring, int startIndex)
Method parameters and return type:
Return type: It returns a last index of a string.
Parameters: It takes a char value, a substring, and an index position from where the index value of a substring of a character value is returned.
Throws: It throws NullPointerException if the string is null or the start index is less than 0 or greater than the length of a string.
Example 1:
In this example, we have used this method in two different ways. Firstly, we have simply passed a character as an argument, and the method will return its index in the given string. After that, we again used this method, but this time, we passed two arguments. The first argument is a character, and the second argument is the index. The method will search for the index of the character after the index that was passed as arguments in the method.
Source code:
public class Example1 {
public static void main(String args[]) {
String str = "Hi! This is Java tutorial";
int index = str.lastIndexOf('t');
System.out.println(index);
index = str.lastIndexOf('s',12);
System.out.println(index);
}
}
Output:
run:
19
10
BUILD SUCCESSFUL (total time: 0 seconds)
Example 2:
You can use his method to check the index of the substring.
Source code:
public class Example2 {
public static void main(String[] args) {
String s = "Welcome to the Java tutorial";
int i = s.lastIndexOf("the");
System.out.println(i);
}
}
Output:
run:
11
BUILD SUCCESSFUL (total time: 1 second)
Example 3:
Here we have searched for the index of a substring after a specific index.
Source code:
public class Example3 {
public static void main(String[] args) {
String s = "Hello Java Programmers!";
int i = s.lastIndexOf("Java", 20);
System.out.println(i);
i = s.lastIndexOf("Programmers", 12);
System.out.println(i);
}
}
Output:
run:
6
11
BUILD SUCCESSFUL (total time: 0 seconds)
References:
Happy Learning 🙂