STRING INSTANCE METHODS

Java String lastIndexOf() method

lastIndexOf() searches for the last occurrence of a character or substring in a specific String object. It returns the matching index, or, if absent, -1.

Finding the last position

String tekstas = "Java yra kalba. Java yra platforma.";

System.out.println(tekstas.lastIndexOf('a'));
System.out.println(tekstas.lastIndexOf("Java"));
System.out.println(tekstas.lastIndexOf("Python"));
Console output

33
16
-1

  1. tekstas stores a sentence in which the word Java occurs twice.
  2. lastIndexOf('a') searches from the end and returns the last occurrence of the letter a at index 33.
  3. lastIndexOf("Java") finds the last word Java starting at index 16.
  4. Python is absent, so the final call returns -1.

Method syntax and overloads

public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)

lastIndexOf() variants
VariantPurpose
lastIndexOf(int ch)Finds the last occurrence of the specified character.
lastIndexOf(int ch, int fromIndex)Searches backwards for a character from the specified index.
lastIndexOf(String str)Finds the last occurrence of the specified substring.
lastIndexOf(String str, int fromIndex)Searches backwards for a substring from the specified index.
Return typeint – the matching index or -1.

The parameter type is inteven for a single character, because the method accepts a Unicode code point. You can conveniently pass an ordinary character as a char, for example, 'a'; Java converts it to a numeric value automatically.

Why is lastIndexOf() an instance method?

lastIndexOf() is called on a specific string because the search happens inside that String object:

int indeksas = tekstas.lastIndexOf('a');

String tekstas = "JavaQuest";

int indeksas = tekstas.lastIndexOf('a');

System.out.println(indeksas);
Console output

3

We therefore do not write String.lastIndexOf(...). On the left, tekstas specifies the character sequence to search.

String tekstas = "bananas";

System.out.println(tekstas.lastIndexOf('a'));
System.out.println(tekstas.lastIndexOf('n'));
Console output

5
4

  1. In the text bananas , the letter a occurs at indices 1, 3 and 5.
  2. lastIndexOf('a') chooses the largest of these indices, returning 5.
  3. The letter n occurs at indices 2 and 4.
  4. Its last occurrence is at index 4.
String failas = "ataskaita.txt.backup.txt";

System.out.println(failas.lastIndexOf(".txt"));
Console output

20

When passed a String, the result is the starting index of the last complete match. In the text ataskaita.txt.backup.txt , the last .txt starts at index 20.

Searching backwards from fromIndex

String tekstas = "Java Java Java";

System.out.println(tekstas.lastIndexOf("Java"));
System.out.println(tekstas.lastIndexOf("Java", 9));
System.out.println(tekstas.lastIndexOf("Java", 4));
Console output

10
5
0

  1. Without fromIndex , the method finds the last Javastarting at index 10.
  2. lastIndexOf("Java", 9) starts searching at index 9 and moves backwards, so the match at index 10 is not considered.
  3. The nearest earlier Java starts at index 5.
  4. Starting at index 4leaves only the first match at index 0.

fromIndex is included in the search. It specifies where to begin moving backwardsrather than the search's lower bound.

A missing value returns -1

String tekstas = "JavaQuest";
int indeksas = tekstas.lastIndexOf("Python");

if (indeksas == -1) {
  System.out.println("Nerasta");
} else {
  System.out.println("Rasta indekse " + indeksas);
}
Console output

Nerasta

-1 is not a real string index: it signals no match. Check the result before passing it to methods such as substring() or charAt().

Practical example: extracting a filename

String kelias = "/kursai/java/pamoka.java";
int paskutinisSkirtukas = kelias.lastIndexOf('/');

String failoVardas = paskutinisSkirtukas == -1
    ? kelias
    : kelias.substring(paskutinisSkirtukas + 1);

System.out.println(failoVardas);
Console output

pamoka.java

  1. lastIndexOf('/') finds the last path separator.
  2. If no separator were found, paskutinisSkirtukas were -1 and the whole text would already be the filename.
  3. If a separator is found, substring(paskutinisSkirtukas + 1) starts copying immediately after it.
  4. This extracts the final path segment, pamoka.java.

The difference from indexOf()

String tekstas = "Java Java Java";

System.out.println(tekstas.indexOf("Java"));
System.out.println(tekstas.lastIndexOf("Java"));
Console output

0
10

indexOf() and lastIndexOf() comparison
The methodSearch directionReturned match
indexOf()From start to endFirst, at index 0
lastIndexOf()From end to startLast, at index 10

Uppercase and lowercase letters differ

String tekstas = "Java java JAVA";

System.out.println(tekstas.lastIndexOf("Java"));
System.out.println(tekstas.lastIndexOf("java"));
Console output

0
5

lastIndexOf() compares exact character contents. Java, java and JAVA are different sequences, so each search may return a different position.

fromIndex outside the string

String tekstas = "Java Java";

System.out.println(tekstas.lastIndexOf("Java", 100));
System.out.println(tekstas.lastIndexOf("Java", -1));
Console output

5
-1

An oversized fromIndex causes no error: the method starts at the end and can find the last match. A negative fromIndex lies before the first character, leaving no position to search, so it returns -1.

Searching for an empty string

String tekstas = "Java";

System.out.println(tekstas.lastIndexOf(""));
System.out.println(tekstas.lastIndexOf("", 2));
Console output

4
2

An empty string exists at every valid position, including immediately after the last character. Therefore, "Java".lastIndexOf("") returns the string length, 4, while searching backwards from index 2 returns 2.

You cannot search for a null substring

String tekstas = "Java";

System.out.println(tekstas.lastIndexOf(null));
Result

NullPointerException

Passing null to lastIndexOf(String str), Java has no sequence to search for and throws NullPointerException. If the search value may be null, check it before calling the method.

Common mistakes

  • Forgetting that indices start at 0.
  • -1 is used as a real index although it means “not found”.
  • Expecting the first match when lastIndexOf() returns the last.
  • fromIndex is treated as a forward-search endpoint, although the method searches backwards from it.
  • Overlooking that the method is case-sensitive.
  • Passing to the substring overload a null value.
  • Forgetting to add 1 to the separator's index before calling substring().

When should you use lastIndexOf()?

Use lastIndexOf()when the last character or substring occurrence matters: extracting filenames from paths, finding the final extension dot, splitting at the last delimiter or analyzing repeated values. For the first match, choose indexOf().