Explain the usage of indexOf() and lastIndexOf() methods with one example each
Answer:-
indexOf() and lastIndexOf() Methods in Java
Both methods are used to find the position (index) of characters or substrings in a String. They return the zero-based index of the match.
1. indexOf()
- Returns the index of the first occurrence of a character or substring.
- If not found, returns
-1.
Syntax:
int indexOf(int ch) int indexOf(String str) int indexOf(int ch, int fromIndex) int indexOf(String str, int fromIndex)
Example:
public class IndexOfExample {
public static void main(String[] args) {
String str = "Java Programming";
int index = str.indexOf("a");
System.out.println("First occurrence of 'a': " + index);
}
}
Output:
First occurrence of 'a': 1
2. lastIndexOf()
- Returns the index of the last occurrence of a character or substring.
- If not found, returns
-1.
Syntax:
int lastIndexOf(int ch) int lastIndexOf(String str) int lastIndexOf(int ch, int fromIndex) int lastIndexOf(String str, int fromIndex)
Example:
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Java Programming";
int index = str.lastIndexOf("a");
System.out.println("Last occurrence of 'a': " + index);
}
}
Output:
Last occurrence of 'a': 3
Summary
| Method | Description | Returns |
|---|---|---|
indexOf() | Index of first match | First match index or -1 |
lastIndexOf() | Index of last match | Last match index or -1 |
