Java String indexOf() Method with Examples

understanding the indexOf() method is necessary for effective string handling. this method helps in locating specific elements within strings, offering flexibility with its different syntaxes.

Whether you’re searching for individual characters or substrings or need to start your search from a specific index, indexOf() is a fundamental method for string manipulation in Java. As you dive deeper into Java programming, you’ll frequently utilize this method to enhance the efficiency and precision of your code.

What is the indexOf() method in Java?

The indexOf() method in the Java String class is designed to provide the position of the initial occurrence of a specified character or substring within a given string. This function serves the purpose of identifying and locating the first instance of the specified character or substring, thereby helping in efficient string manipulation and analysis in Java programming.

Syntax of indexOf() in Java

The IndexOf() method in Java has four different syntaxes that can be varied according to the input parameters passed. Let us take a deeper look at each variation of the indexOf() method, and while we are at it, let us consider an example program to better understand its workings.

1. int indexOf(int ch)

This syntax variant is used to find the index position of a specified character (ch) within the string. The method takes a single parameter, ch, representing the character to search for. It returns an integer indicating the index of the first occurrence of the character in the string.

public class Main 
{
    public static void main(String args[])
    {
        String str= new String("FirstCode is amazing");
        System.out.println("Index of first 'C': "+str.indexOf('C'));
    }
}

Output:
Index of first ‘C’: 5

The above-shown code outputs “Index of first ‘C’: 5.” This is because the indexOf method returns the index of the first occurrence of the specified character in the string.

In the given string “FirstCode is amazing”, the first occurrence of the character ‘C’ is at index 5 (0-based indexing), and that’s what is printed to the console. Therefore, the output indicates that the first ‘C’ in the string is found at index 5.

2. int indexOf(int ch, int fromIndex)

In this variation, the method allows users to specify both the character to search for (ch) and a starting index (fromIndex). The two parameters are “ch” and “parameterfromIndex”.

“ch” is the character to locate within the string, and “parameterfromIndex” is the index from which the search begins. The method returns an integer representing the index of the first occurrence of the character within the specified range.

public class Main 
{
    public static void main(String args[])
    {
        String str= new String("FirstCode is amazing");
        System.out.println("Index of second 'i': "+str.indexOf('i', 2));
    }
}

Output
Index of second ‘i’: 10

In the above code, the output is “Index of second ‘i’: 10.” This is because the indexOf method starts searching for the specified character (‘i’) from the given starting index (2) in the string “FirstCode is amazing.”

The first occurrence of ‘i’ is at index 2, but the search for the second ‘i’ begins from index 2 onwards. The second occurrence of ‘i’ is found at index 10 (indexing starts with 0), and that’s what is printed to the console. Therefore, the output indicates that the second ‘i’ in the string is found at index 10.

3. int indexOf(String substring)

This syntax is tailored for finding the index position of a specified substring within the string. The method accepts a single parameter, substring, representing the substring to search for. It returns an integer indicating the index of the first occurrence of the substring.

public class Main 
{
    public static void main(String args[])
    {
        String str1 = new String("FirstCode is always First");
        String str2 = new String("First");
        System.out.println("Index of first 'First': "+str1.indexOf(str2));
    }
}

Output:
Index of first ‘First’: 0

The code shown above outputs “Index of first ‘First’: 0.” This is because the indexOf method returns the starting index of the first occurrence of the specified substring (str2) in the calling string (str1).

In this case, the substring “First” is found at the very beginning of the string “FirstCode is always First”, starting from index 0. Therefore, the output indicates that the first occurrence of the substring “First” in the string is found at index 0.

4. int indexOf(String substring, int fromIndex)

This variant combines substring and starting index parameters, enabling users to search for a substring starting from a specific index. The method takes two parameters: “substring” and “fromIndex.”

“Substring” is the substring to locate within the string, and “fromIndex” is the index from which the search begins. The method returns an integer representing the index of the first occurrence of the substring within the specified range.

public class Main 
{
    public static void main(String args[])
    {
        String str1 = new String("FirstCode is always First");
        String str2 = new String("First");
        System.out.println("Index of second 'First': "+str1.indexOf(str2, 2));
    }
}

Output:
Index of second ‘First’: 20

The code shown above outputs “Index of second ‘First’: 20.” This is because the indexOf method starts searching for the specified substring (str2) from the given starting index (2) in the calling string (str1).

The first occurrence of “First” is found at index 0, but the search for the second occurrence begins from index 2 onwards. The second occurrence of “First” is found at index 20 (0-based indexing), and that’s what is printed to the console. Therefore, the output indicates that the second occurrence of the substring “First” in the string is found at index 20.

Using indexOf() to check if a character is a vowel or not

class FirstCode 
{
    public static boolean vowel(char c)
    {
        return "aeiouAEIOU".indexOf(c) >= 0;
    }
    public static void main(String[] args)
    {
        boolean isVowel = vowel('I');
        if (isVowel) System.out.println("It is a Vowel");
        else System.out.println("It is a Consonant");
    }
}

Output:

It is a Vowel

In the Java code shown above, a class named FirstCode is defined with a method called vowel, which takes a character as a parameter and checks if it is a vowel. The method uses the indexOf method on the string “aeiouAEIOU” to determine whether the given character is present in the string of vowels. If the index is greater than or equal to 0, it means the character is found in the string, indicating that it is a vowel, and the method returns true.

In the main method, the vowel method is invoked with the character ‘I’. The result is stored in the variable “isVowel.” Subsequently, a conditional statement checks whether isVowel is true or false. If isVowel is true, the code prints “It is a Vowel” to the console; otherwise, it prints “It is a Consonant.”

Since ‘I’ is a vowel, the code output is “It is a Vowel.” The vowel method correctly identifies that ‘I’ is present in the string of vowels, and the conditional statement prints the appropriate message to the console based on the result of the vowel check.

Conclusion

In conclusion, the indexOf() method in Java is a versatile tool for developers to locate the position of characters or substrings within a given string. The method has four different variations, accommodating various use cases by enabling the specification of characters, substrings, and starting indices.

Through examples provided in this article, we’ve learned how to use each syntax to find the index of characters or substrings, making it a valuable asset for tasks such as searching, parsing, and validation in Java programming.

Leave a Reply

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