Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.lastIndexOf()

Finds the position of the last occurrence of a character or a substring.

Available since: Java 1.0

Syntax

public int lastIndexOf(String str)

Parameters

ParameterTypeDescription
strStringWhat to look for — a string or a char.

Return value

intThe index of the last occurrence, or -1.

Examples

The last occurrence:

void main() {
    IO.println("banana".lastIndexOf('a'));
    IO.println("banana".lastIndexOf("an"));
}

Output:

5
3

A file extension — everything after the last dot:

void main() {
    String file = "report.final.pdf";
    String ext = file.substring(file.lastIndexOf('.') + 1);
    IO.println(ext);
}

Output:

pdf

Notes

If there is no dot, lastIndexOf('.') returns -1 and substring(0) returns the whole string. Check for -1 when it matters.

See also

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.