The string indexOf method in Java

The Java indexOf method returns the index of a given character or substring for the first occurrence in the specified string. The search starts from the beginning or specified index position.

This may be useful in scenarios (for example) where you just need to confirm if the given substring or single character exists in the target string or not.

Note: To get the last occurrence of the given substring or character, use the lastIndexOf() method. Learn more about this with an example in the later part of this tutorial.

How to use the indexOf() method?

Following is the syntax for using the indexOf method with variations:

The first way of searching substring:

public int indexOf(String sub_str)

  • In this way, the given substring is searched from the beginning of the specified string.

Second Way:

indexOf(String sub_str, int fromIndex)

  • In this variation, the searching of the given sub_str starts from the specified index position.
  • The second parameter, fromindex specifies where to start searching in the given string. This is an integer that starts with 0 index.

The third way of searching a character:

public int indexOf(int ch)

  • The index of the first occurrence of the char value in the specified string is returned. The string searching starts at 0 or the beginning of the string.

Fourth way:

indexOf(String str, int fromIndex)

  • The searching for the given char character starts at the fromindex number.

In all variations, these are the common points of using the indexOf method:

  • The index starts at 0 the position.
  • The indexOf Java returns index position if the substring is found.
  • It returns -1 if the given sub_str is not found.
  • The returned value is an int.

See the examples of using Java string indexOf() method in next section. The last part shows how to use the lastIndexOf() method.

An example of string indexOf() method with substring

For the example, a string is created with repetitive words. After that, the indexOf method is used to establish if the given substring “is” exist in the string or not:

public class search_demo {

          public static void main(String args[]) {

                    String strIndOf = new String("This is Java String indexOf method. Java is cool.");

                    int x;              



                    //Using indexOf method for substring

                     x = strIndOf.indexOf("Java");



                     if (x > -1) {

                        System.out.print("The indexOf 'Java' is: " + x );

                             }

                     else {

                        

                       System.out.println("The given substring does not exist");

               }

                }

}

Output:

string indexOf

You can see, the occurrence of the word “Java” is twice in the given string. However, the indexOf Java method returned the first occurrence which is at the 8th position.

What if given substring does not exist?

For this example, the Scanner class is used to take the user input. The input string is then searched by indexOf method to check whether it occurs in the string or not. I entered different strings and see the output:

import java.util.Scanner;

public class search_demo {

          public static void main(String args[]) {

                    String strIndOf = new String("This is Java String indexOf method. Java is cool.");



                    //Taking the user input

                    Scanner readInput = new Scanner(System.in);  // Reading from System.in

                        System.out.println("Enter a Substring to search: ");

                        String substr = readInput.next();                 

                    int x;              



                    //Using indexOf method for substring

                     x = strIndOf.indexOf(substr);



                     if (x > -1) {

                        System.out.print("The indexOf 'Java' is: " + x );

                             }

                     else {

                        

                       System.out.println("The given substring does not exist");

               }

                     readInput.close();

                }

}

The output:

Enter a Substring to search:

method

The index Of method : 28

Enter a Substring to search:

awesome

The given substring does not exist



Enter a Substring to search:

indexOf

The index Of indexOf : 20

You see, the substring “awesome” did not exist in the source string so indexOf method returned -1 and else part executed.

The example of using character in indexOf method

Similarly, you may use the Java String indexOf method for searching a character. The character is enclosed in the single quote unlike the strings in double quotes. No fromIndex parameter is given, so searching will start from the beginning of the given string:

public class search_demo {

          public static void main(String args[]) {

                    String strIndOf = new String("Search a char using indexOf");

                    int x;              



                    //Using indexOf method for char

                     x = strIndOf.indexOf('c');



                        System.out.print("The indexOf 'c' is: " + x );

                }

}

The output:

Java indexOf

Using fromindex parameter example

The word “Java” is used twice in the string where we want to search the substring. In the indexOf method, the fromindex parameter is also given:

public class search_demo {

          public static void main(String args[]) {

                    String strIndOf = new String("Java Strings. Java is cool.");

                    int x;              



                    //Using indexOf method for substring

                     x = strIndOf.indexOf("Java", 10);



                        System.out.print("The indexOf 'Java' with from index : " + x );





                }

}

The result:

The indexOf ‘Java’ with from index : 14

Although the first occurrence of “Java” is at 0 position, however, it returned the index of the second occurrence as we gave from index = 10.

Using the Java lastIndexOf method example

The lastIndexOf() method works the same way as indexOf method except it returns the index of the last occurrence of the given search term. Just like the indexOf() method, you may search the strings and character by using the lastIndexOf() method.

public class search_demo {

          public static void main(String args[]) {

                    String strIndOf = new String("Java Strings. Java is cool.");

                    int x;              



                    //Using lastIndexOf method for substring

                     x = strIndOf.lastIndexOf("Java");



                        System.out.print("Using lastIndexOf, the index is : " + x );



                }

}

string lastIndexOf

You see, it returned 14 which is the position of the last occurrence of the term “Java”.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!