Java String lastIndexOf example

String’s lastIndexOf method is used to find out last index of any character or sub string.

lastIndexOf method can take char or string as argument and also you can provide fromIndex also.

Methods:

public int lastIndexOf(int ch)
returns index of last occurrence of character within String

public int lastIndexOf(int ch,int fromIndex)
returns index of last occurrence of character within String, going backward from specific index “fromIndex”

public int lastIndexOf(String)
returns index of last occurrence of substring within String

public int lastIndexOf(int ch,int fromIndex)
returns index of last occurrence of substring within String, going backward from specific index “fromIndex”

All lastIndexOf methods return -1 if char or substring is not present in the String

String indexOf Example:

When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *