What is Java String indexOf()?

As a Java developer, you must have come across the need to find the position of a character or a substring within a string. Java provides a built-in method called indexOf() in the String class to help us with this task. The indexOf() method in Java is a part of the String class, i.e. Java String class indexOf(), which is used to manipulate strings. The indexOf() method in Java returns the position of the first occurrence of a character or a substring within a given string. If the character or substring is not found, the method returns -1.

// Here is the syntax of the String indexOf():
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
Let's dive into the different ways in which we can use the `indexOf()` method.

Finding the position of a character in the string:

Suppose we have a string "Hello, world!". To find the position of the character 'o' in the string, we can use the following code:

public class StringIndexOfExample {
    public static void main(String[] args) {
        String str = "Hello, world!";
// We will use Str.indexOf here
        int position = str.indexOf('o');
        System.out.println("Position of 'o' in the string is: " + position);
    }
}

Output

Position of 'o' in the string is: 4
In the above code, we first declared a string "Hello, world!" and then used the indexOf() method to find the position of the character 'o' in the string. The method returned position 4, which is the first occurrence of the character 'o' in the string.

Finding the position of characters in a string

Here's an example code snippet that demonstrates how to use the indexOf() method to find the position of characters in a string:

public class StringIndexOfExample {
    public static void main(String[] args) {
        String str = "Hello, world!";
        // We will use Str.indexOf here
        int position = str.indexOf('o');
        
        while (position >= 0) {
            System.out.println("'o' found at position " + position);
            position = str.indexOf('o', position + 1);
        }
    }
}

Output

'o' found at position 4 'o' found at position 8
In the above code, we first declared a string "Hello, world!" and then used the indexOf() method to find the position of the character 'o' in the string. The indexOf() method returns the position of the first occurrence of the character in the string, or -1 if the character is not found. We then used a while loop to continue searching for the character 'o' in the string by calling indexOf() with the character and the next starting position as arguments. We repeat this process until indexOf() returns -1, indicating that there are no more occurrences of the character in the string. In this example, we found that the character 'o' appears at positions 4 and 8 in the string "Hello, world!".

Finding the position of a substring in the string

Suppose we have a string "Java is a popular programming language". To find the position of the substring "programming" in the string, we can use the following code:

public class StringIndexOfExample {
    public static void main(String[] args) {
        String str = "Java is a popular programming language";
        // We will use Str.indexOf here
        int position = str.indexOf("programming");
        System.out.println("Position of 'programming' in the string is: " + position);
    }
}

Output

Position of 'programming' in the string is: 18
In the above code, we first declared a string "Java is a popular programming language" and then used the indexOf() method to find the position of the substring "programming" in the string. The method returned the position 18, which is the starting position of the substring "programming" in the string.

Finding all occurrences of a character or substring in the string

Suppose we have a string "Java is a popular programming language. Java is widely used in web development". To find all occurrences of the character 'a' or the substring "Java" in the string, we can use the following code:

public class StringIndexOfExample {
    public static void main(String[] args) {
        String str = "Java is a popular programming language. Java is widely used in web development.";

        int position = -1;


        while ((position = str.indexOf('a', position + 1)) != -1) {
            System.out.println("Found 'a' at position: " + position);
        }

        while ((position = str.indexOf("Java", position + 1)) != -1) {
            System.out.println("Found 'Java' at position: " + position);
        }
    }
}

Output

Found 'a' at position: 1 Found 'a' at position: 3 Found 'a' at position: 8 Found 'a' at position: 15 Found 'a' at position: 23 Found 'a' at position: 31 Found 'a' at position: 35 Found 'a' at position: 41 Found 'a' at position: 43 Found 'Java' at position: 0 Found 'Java' at position: 40
In the above code, we first declared a string "Java is a popular programming language. Java is widely used in web development" and then used the indexOf() method to find all occurrences of the character 'a' or the substring "Java" in the string. We used a while loop to iterate over all occurrences of the character or substring until the indexOf() method returns -1, which indicates that there are no more occurrences of the character or substring in the string. Java String indexOf() - 1

Method options indexOf

The method java string indexOf has four different variations:

1. indexOf (int ch)

The method int indexOf(int ch) returns the index in the given string of the first occurrence of the specified character. In other words, we will get the number of the first occurrence of the given character, counting from left to right. Example:
public static void main(String[] args) {
   String str = "Diego, where is my money?";
   int value = str.indexOf('e');
   System.out.println(value);
}
Console output:

2
If the character we are looking for is not in the given string, we will get -1.
public static void main(String[] args) {
   String str = "Diego, where is my money?";
   int value = str.indexOf('j');
   System.out.println(value);
}
Console output:

-1
In order not to confuse anything, you need to remember that the characters in the line are counted not from “‎1,2,3…”, but from “‎0,1,2...”‎

2. indexOf (int ch, int fromIndex)

The method int indexOf(int ch, int fromIndex) returns the index in this string of the first occurrence of the specified character, starting the search at the specified index. This method is a more modernized version of the previous one. The difference is that we indicate the number of the element from which the search will actually begin. Example:
public static void main(String[] args) {
   String str = "Diego, where is my money?";
   int value = str.indexOf('e',5);
   System.out.println(value);
}
Console output:

9
If the index from which to search is greater than the length of the string, then the answer is -1. As you may have noticed, in the signature of these two methods (what the methods take as arguments), the type for the character being passed is specified as int, not char. However, we have passed on char. This is because the strings are stored as an array of bytes, where the cells correspond to a certain character of type char. The correspondence between bytes and char is carried out according to the ASCII table. ASCII (American Standard Code for Information Interchange) is a table that maps common printable and non-printable characters to numeric codes. So when a character is passed char, it is automatically converted to the number that the given character represents in the ASCII table. Based on this, we can directly pass a number (int) to the method that corresponds to the character we need. For example, the character 'e' in the ASCII table corresponds to the number 101, so we can repeat the previous example, but without the char:
public static void main(String[] args) {
   String str = "Diego, where is my money?";
   int value = str.indexOf(101,5);
   System.out.println(value);
}
Our console output has not changed:

9
In some cases, these methods are interchangeable, as for example, str.indexOf('e'); it will be similar - str.indexOf('e', 0);.

3. indexOf (String str)

The method int indexOf(String str) returns the index in the given string of the first occurrence of the specified substring. It is fundamentally different from the first option in that this method is already looking for a whole substring (String). Thanks to this, we can already look for something more specific. Example:
public static void main(String[] args) {
   String str = "Diego, where is my money? Diego,you made me very upset";
   int value = str.indexOf("Diego");
   System.out.println(value);
}
Console output:

0
All variations indexOf are case sensitive: upper case characters (large letters) and lower case characters (small letters) are treated as different. Be careful.

4. indexOf (String str, int fromIndex)

The method indexOf(String str, int fromIndex) returns the index within this string of the first occurrence of the specified substring, starting at the specified index. This option is again a more modernized previous version, but with an indication of the place from which the search will be conducted. Example:
public static void main(String[] args) {
   String str = "Diego, where is my money? Diego,you made me very upset";
   int value = str.indexOf("Diego", 1);
   System.out.println(value);
}
Console output:

26
If you set a negative start index, the method indexOf will take it as 0. In this case, the method will again become similar to the previous one (in which the start index is not specified). It's all for today. Now your stock of knowledge is bigger thanks to indexOf Java!

Conclusion

In conclusion, the indexOf() method in Java is a powerful tool to find the position of a character or a substring within a string. By using the different variations of the method, we can easily find the position of a character or substring in a string, starting from a given index or finding all occurrences of a character or substring. It is an essential method for any Java developer working with strings in their applications.