Java .lastIndexOf()

Anonymous contributor's avatar
Anonymous contributor
Published Mar 2, 2023
Contribute to Docs

The .lastIndexOf() method searches a string for a specified value and returns the position of the match. It searches the string, from the end to the beginning, and returns the index of the specified value. In other words, it returns the index of the last occurrence of the specified value. Otherwise if the value is not found, it returns -1.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

string.lastIndexOf(searchValue, fromIndex)
  • searchValue: The character or sequence of characters being searched for.
  • fromIndex (optional): The starting index to search from in the string.

Example

This example below searches the string sentence for the value 'the' and returns the index of the last occurrence:

class Main {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog";
int lastPos = sentence.lastIndexOf("the");
System.out.println(lastPos);
}
}

This will output the following:

31

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours