IndexOf() Java Method Explained [Easy Examples]


JAVA

Author: Bashir Alam
Reviewer: Deepak Prasad

 

Introduction to IndexOf() Java method

The IndexOf() Java method finds the index position at which a specified string begins. This method helps us to find a string within another string. The indexOf java method returns the index of a particular character or substring in a string. In this tutorial, we will learn about the IndexOf() java method. We will learn how we can use this method to find the position of a substring within a string.

We will also cover the type of the different types of parameters that this method can take along with taking various examples. Moreover, we will also see what will happens if we try to find the position of a substring that is not in a string. All in all, this is going to be one of the most detailed tutorials about the java IndexOf() method.

 

Getting Started with IndexOf() Java method

The IndexOf() Java method is really helpful in practical cases. For example, let us say we have a list of items to buy from the shop and we just wanted to know if we had added bananas to our list or not. Instead of going through the list manually and checking each item, we can use the java IndexOf() method which will return the index position banana if we had added it to our list. In such cases, the IndexOf() method is really useful and time-saving. In this section, we will look at the basic syntax and will take some examples related to the IndexOf() java method.

 

Different Syntax to use IndexOf() in Java

A Java String is a sequence of characters that exist as an object of the class java. You can read more about strings from the article on Java strings. The indexOf() method is used to get the index of the first occurrence of a specified character/string in the parameter of the IndexOf method of a string. The IndexOf() java method can take one parameter ( char or string) or two parameters as well. The simple syntax of the IndexOf() java method with one parameter looks like this:

StringName.IndexOf(char);

If we want to find the position of a substring rather than a char value, then we can use the following syntax.

StringName.IndexOf(Substring);

The IndexOf() method also takes an optional parameter of starting index position as well.  The IndexOf() method will start checking the occurring of the specified string/char from the starting index. The simple syntax of the IndexOf() java method with two parameters looks like this.

StringName.IndexOf(char, startingPosition);

And with substring value, the syntax will look like this;

StringName.IndexOf(string, startingPosition);

All of the above different syntaxes of the Java IndexOf() method return an integer value which will be the first occurrence of specified char/string in the main string.

 

How to use IndexOf() in Java

Now see the diagram below which differentiates between the indexof java method with one parameter and indexof java method with two parameters.

Indexof java

 

IndexOf() Java method with one parameter

We already discussed that the IndexOf() java takes one required and one optional parameter. The required parameter can either be a char value or a string value. In this section, we will take examples of both char and a string value as parameters to the IndexOf() java method.

 

Example-1: IndexOf() Java method and Char parameter

Let us take an example of a string and then find the position of the specified character in the string. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "string";
       // indexof java  
       System.out.println("the index position of t is :"+string.indexOf('t'));
    }
}

Output:

the index position of t is :1

Notice that it give the position of t as 1, not 2 because the indexing in java starts from zero, not from one.

 

Example-2: IndexOf java method and duplicate char values

Now let us find the position of duplicate char values and see how we will get the return value. See the example below which applies the IndexOf() java method on duplicate char values in a string.

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "sssssssssss";
       // indexof java  
       System.out.println("the index position of s is :"+string.indexOf('s'));
    }
}

Output:

the index position of s is :0

Notice that we get the position of the very first occurring specified elements and the rest have been ignored by the java IndexOf() method.

 

Example-3: IndexOf() Java method and String parameter

In a similar, way we can provide a substring value instead of a char value as a parameter and it will return the index position of the substring. See the example below which uses a substring as a parameter.

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "welcome to go linux cloud";
       // indexof java  
       System.out.println("the index position of substring is :"+string.indexOf("linux"));
    }
}

Output:

the index position of substring is :14

Notice that we get the index of the starting of the substring in our main string.

 

Example-4: IndexOf() java method and duplicate string values

The IndexOf() java method works in a similar way when a substring is provided as a parameter as it works for char values. See the example below which returns the index position of the first occurrence of substring.

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "golinuxcloud golinuxcould golinuxcloud";
       // indexof java  
       System.out.println("the index position of substring is :"+string.indexOf("golinuxcloud"));
    }
}

Output:

the index position of substring is :0

Notice that it returns the very first position where the specified substring starts.

 

IndexOf() Java method with two parameters

We already had discussed that the java IndexOf() method can take an optional parameter along with a specified char or substring, which will be starting the search for the specified char/string value. The optional parameter is useful when we are sure that the char/substring can be found in some range of indexes.  In this section, we will take some examples of the IndexOf() method along with various examples.

 

Example-1: IndexOf() Java method with char value and starting parameter

Now let us take an example of the java IndexOf() method which takes two parameters. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "welcome to go linux cloud";
       // indexof java  
       System.out.println("the index position of char is :"+string.indexOf('o', 10));
    }
}

Output:

the index position of char is :12

Notice that there were "o" characters at positions 4 and 9 respectively but they were ignored by the java IndexOf method because we specified the starting position to be 10.

 

Example-2: IndexOf() Java method with String and starting parameter

In a similar way, we can provide the starting index along with a substring and it will return the position of the substring after the specified index. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "golinuxcloud golinuxcloud golinuxcloud";
       // indexof java  
       System.out.println("the index position of substring is :"+string.indexOf("golinuxcloud", 10));
    }
}

Output:

the index position of substring is :13

Notice that the search for the specified substring starts from the provided starting index, not from the index 0.

 

Handling a string that is not present

So far we have taken examples and scenarios where the specified string/char value was present in our main string. In this section, we will see what will happen if we provide a string/char value that is not present in our main string and how to handle such scenarios to get logical returned values.

 

Example-1: IndexOf() Java method and char value not present in the string

Let us take an example of the java IndexOf() method and provide a char value as a parameter that will not be in the main string. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "golinuxcloud";
       // indexof java  
       System.out.println("the index position of z is :"+string.indexOf('z'));
    }
}

Output:

the index position of z is :-1

Notice that we get a value of -1 which means the value is not found in the main string.

 

Example-2: IndexOf() Java method and handling string not present case

We already know that if a string/char value is not present in our main string, then the index of the java method will return -1. Let us now use if-else statements to handle this case and print out a valid and meaningful message. You can read more about if-else statements from the article if else java statements.  See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // java string
       String string = "golinuxcloud";
       // if-else statement
       if(string.indexOf('z')>=0){
            // indexof java  
            System.out.println("the index position of z is :"+string.indexOf('z'));
       }else{
           System.out.println("the specified char value is not found!!");
       }
       
    }
}

Output:

the specified char value is not found!!

Notice that this time we get a meaningful message rather than -1 value for not founding a specified char/string value.

 

Summary

The indexOf Java method returns the index within the calling String object of the first occurrence of the specified value. It can also take an optional parameter to start the search from the specified position. In this article, we learned about the java IndexOf() method. We covered the basic syntax and learned how we can use the java IndexOf() method to find the position of char or a string value from a string by taking various examples.

Moreover, we also discussed how to handle the output if the specified char/string is not found. All in all, this tutorial contains all the necessary information and examples that you need to know in order to start working with the IndexOf() java method.

 

Further Reading

Java IndexOf() method
IndexOf() method documentation
Java strings

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment