Java String lastIndexOf() Method Tutorial

In this section, we will learn what the String lastIndexOf() method is and how to use it in Java.

What is Java String lastIndexOf() Method?

The Java String lastIndexOf() method is used to check a string value and see if it has a specific character or a sequence of characters in it or not.

Java lastIndexOf() Method Syntax:

public int lastIndexOf(String str)

public int lastIndexOf (String str, int fromIndex)

public int lastIndexOf (int char)

public int lastIndexOf (int char, int fromIndex)

lastIndexOf() Method Parameters:

As you can see, the method has 4 variants.

  • `str`: this is the string that we want to search for it in the target string and see if it has such value or not.
  • `fromIndex`: inside the target string if we want to start from a specific index, we can add that index as the second argument to the method.

Note: by default, the search begins from the last element of the target string and moves toward the beginning of that string.

  • `char`: if we want to look for a character in the target string, we can put that character as the first argument to the method.

lastIndexOf() Method Return Value:

If in the target string there was the character that we set as the argument of the method, the index number of the LAST occurrence will return. Otherwise if it wasn’t found, the value -1 will return instead.

lastIndexOf() Method Exceptions:

This method does not throw an exception.

Example: using String lastIndexOf() method

public class Simple {

    public static void main(String[] args)  {
        String s1 = "imitation";





Top Technologies