The lastIndexOf() method in Java is a method of the String class. It is used to find the last occurrence (the rightmost occurrence) of a specified character or substring in a given string.
Find the last occurrence of a specified character
Syntax:
public int lastIndexOf(int ch)
int ch – A character (specified by its Unicode value) to search for.
Example:
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World!";
// Find the last occurrence of the character 'o'
int index = str.lastIndexOf('o');
System.out.println("Last index of 'o': " + index);
}
}
Output: Last index of ‘o’: 7
Notes:
- The method returns the index of the last occurrence of the specified character or substring.
- If the character or substring is not found, it returns -1.
Find the last occurrence of a specified string
Syntax:
public int lastIndexOf(String str)
Example:
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World Hello";
// Find the last occurrence of the substring "Hello"
int index = str.lastIndexOf("Hello");
System.out.println("Last index of 'Hello': " + index);
}
}
Output: Last index of ‘Hello’: 12
Find the string not found
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World";
// Find the last occurrence of the substring "Java"
int index = str.lastIndexOf("Java");
System.out.println("Last index of 'Java': " + index);
}
}
Output: Last index of ‘Java’: -1
Find lastIndexOf() with a starting index
You can also specify a starting index from which the search will begin (searching backward).
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World Hello";
// Start search from index 5
int index = str.lastIndexOf("Hello", 5);
System.out.println("Last index of 'Hello' before index 5: " + index);
}
}
Java String lastIndexOf() method – Interview Questions
Q 1: What is lastIndexOf() method used for?
Ans: Finds the last occurrence of a character or substring.
Q 2: What does lastIndexOf() return if not found?
Ans: -1.
Q 3: How is it different from indexOf()?
Ans: It searches from the end of the string.
Q 4: Is lastIndexOf() case-sensitive?
Ans: Yes, it is case-sensitive.c
Q 5: Yes, it is case-sensitive.
Ans: Yes
Java String lastIndexOf() method – Objective Questions (MCQs)
Q1. What does lastIndexOf() method return?
Q2. What will "Programming".lastIndexOf("g") return?
Q3. What is returned if the substring is not found?
Q4. What is the return type of lastIndexOf()?
Q5. What will "Java Programming".lastIndexOf("a", 5) return?