The indexOf()
method in Java is used to find the index of the first occurrence of a character or a substring within a string. If the character or substring is not found, it returns -1
.
Syntax
- For a character:
int indexOf(int ch)
- ch: The character to search for.
- Returns the index of the first occurrence of the character
ch
, or-1
if it’s not found.
- For a substring:
int indexOf(String str)
- str: The substring to search for.
- Returns the index of the first occurrence of the substring
str
, or-1
if it’s not found.
- With a starting index:
int indexOf(int ch, int fromIndex)
- ch: The character to search for.
- fromIndex: The index from which to start searching.
- Returns the index of the first occurrence of
ch
after the specifiedfromIndex
, or-1
if it’s not found.
- For a substring with starting index:
int indexOf(String str, int fromIndex)
- str: The substring to search for.
- fromIndex: The index from which to start searching.
- Returns the index of the first occurrence of
str
after the specifiedfromIndex
, or-1
if it’s not found.
Example Usage
public class Example {
public static void main(String[] args) {
String str = "Hello, world!";
// Searching for a character
int index1 = str.indexOf('o'); // Returns 4
System.out.println("Index of 'o': " + index1);
// Searching for a substring
int index2 = str.indexOf("world"); // Returns 7
System.out.println("Index of 'world': " + index2);
// Searching for a character starting from index 5
int index3 = str.indexOf('o', 5); // Returns 8
System.out.println("Index of 'o' starting from index 5: " + index3);
// Searching for a substring starting from index 5
int index4 = str.indexOf("world", 5); // Returns 7
System.out.println("Index of 'world' starting from index 5: " + index4);
}
}
Key Points:
- If the character or substring is not found,
-1
is returned. - The search is case-sensitive.
- The method can also take a starting index to specify from where to begin the search.