Java StringlastIndexOf() Method
Example
Search a string for the last occurrence of "planet":
String myStr = "Hello planet earth, you are a great planet.";System.out.println(myStr.lastIndexOf("planet"));Definition and Usage
ThelastIndexOf() method returns the position of the last occurrence of specified character(s) in a string.
Tip: Use theindexOf method to return the position of thefirst occurrence of specified character(s) in a string.
Syntax
One of the following:
public int lastIndexOf(Stringstr)public int lastIndexOf(Stringstr, intfromIndex)public int lastIndexOf(intchar)public int lastIndexOf(intchar, intfromIndex)Parameter Values
| Parameter | Description |
|---|---|
| str | AString value, representing the string to search for |
| fromIndex | Anint value, representing the index position to start the search from. If omitted, the default value is the length of the string |
| char | Anint value, representing a single character, e.g 'A', or a Unicode value |
Technical Details
| Returns: | Anint value, representing the index of the first occurrence of the character in the string, or -1 if it never occurs |
|---|
More Examples
Example
Find the last occurrence of "e" in a string, starting the search at position 5:
public class Main { public static void main(String[] args) { String myStr = "Hello planet earth, you are a great planet."; System.out.println(myStr.lastIndexOf("e", 5)); }}❮ String Methods

