Java String lastIndexOf()

The String.lastIndexOf() returns the last index of a specified character(s) or substring. If the argument is not found in the string, the method returns -1. Note that the indices for a string start with zero.

1. String.lastIndexOf() API

The lastIndexOf() method has four overloaded forms.

int lastIndexOf(String substring)
int lastIndexOf(String substring, int fromIndex)

int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)

The method arguments are:

  • substring or ch: the substring or the char to be found.
  • fromIndex: search starts with the specified location in the string.

The method returns the index of the last occurrence of the specified substring, or -1 if there is no such occurrence.

2. String.lastIndexOf() Example

In the following Java program, the substring “Java” appears twice. When we search the string with lastIndexOf(), it returns the position of the last “Java” string. The letter ‘J’ is stored on the index position 41 that we can verify by searching for the character ‘J’.

String str = "Hello world Java programmers, welcome to Java world !";

Assertions.assertEquals(41, str.lastIndexOf("Java"));
Assertions.assertEquals(41, str.lastIndexOf('J'));

Suppose was want to search for the substring from a specific position in the string. For example, we want to know the distance of word “Java” from the comma. We can pass the position of the comma as the second method argument. This time, the ‘Java’ is found at the index position 12.

String str = "Hello world Java programmers, welcome to Java world !";

Assertions.assertEquals(12, str.lastIndexOf("Java", str.indexOf(",")));
Assertions.assertEquals(12, str.lastIndexOf('J', str.indexOf(",")));

3. Null and Empty Strings

Passing null argument is not allowed to lastIndexOf() and will result in NullPointerException exception.

Assertions.assertThrows(NullPointerException.class, ()->{

The position of the empty string is always considered at the end of the string, and the method returns the value calculated by String.length().

Assertions.assertEquals(str.length(), str.lastIndexOf(""));

Happy Learning !!

Reference: Java String doc

Sourcecode on Github


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode