Java String lastIndexOf() Method

Java String lastIndexOf

Well, in some of the above methods, we tried finding the first occurrence index of some string, or some character. If you are wondering that hey… what if we want to get the last occurrence of some string or some character? How can we do that?

Well, for this also, we have some method here for us, which is the lastIndexOf method. Remember that it takes a string or a character as an argument.

In return, it gives the index of the last occurrence of that string or that character. In this method also, we can find that it returns -1 if the string or the character is not present.

Let’s have a look at an example program just to get a clear idea –

public class StringMethods {
public static void main(String[] args) {
String str1 = “This food house serves good food”;
System.out.println(str1.lastIndexOf(“food”));
}
}

So, from the above program, we can comfortably understand that we are searching for the last index of the string ”food”. Executing the program, we find the output to be 28.

Let’s have a program also for searching for a character in the string –

public class StringMethods {
public static void main(String[] args) {
String str1 = “This food house serves good food”;
System.out.println(str1.lastIndexOf(‘o’));
}
}

From the above program, it is clear that we are trying to search for the character ‘o’ in the string. Executing the program, we get the output as 30.