In this Java tutorial, you will learn how to find the index of first occurrence of a search string in a given string using String.indexOf() function, with examples.

Find the first occurrence index of a substring in Java

To get the index of the first occurrence of a substring in a Java string, call indexOf() on the main string and pass the substring as the argument.

</>
Copy
int index = mainString.indexOf(searchString);

The returned index is zero-based. It means the first character of the string is at index 0, the second character is at index 1, and so on. If the substring is not found, indexOf() returns -1.

A string, say str2, can occur in another string, say str1, any number of times. There could be a requirement in your Java application, that you have to find the position of the first occurrence of str2 in str1. Or you may need to find nth occurrence.

In this tutorial, we shall learn to get the index of first occurrence of a string in another string using Java.

We shall make use of String.indexOf(String otherString) method, to find the index of first occurrence of string str2 in str1. If the string str2 is present in the other string str1, it returns the index of its first occurrence. If it is not present, then it returns -1 indicating that the string str2 is not present in the string str1.

Java String indexOf() syntax for first substring match

The commonly used syntax to find the first occurrence of a substring is:

</>
Copy
string.indexOf(substring)
PartMeaning
stringThe main string in which you want to search.
substringThe text you want to find inside the main string.
Return valueThe zero-based index of the first match, or -1 when there is no match.

The method is case-sensitive. For example, "good" and "GOOD" are treated as different strings unless you convert both strings to the same case before searching.

Examples to get the first occurrence of a substring in Java

1. Get the index of first occurrence of a substring

In this example, we shall initialize two strings with variable names str1 and str2. And we are going to find the first occurrence of str2 in str1.

/**
 * Java Example program to find the index of first occurrence of a substring in a string
 */
public class FirstOccurrenceExample {

	public static void main(String[] args) {
		//initialize strings
		String str1 = "hello world good morning. good day.";
		String str2 = "good";

		//get the index of str2 in str1
		int indexOfSubStr = str1.indexOf(str2);
		
		System.out.println("str2 first appeared in str1 at index : "+ indexOfSubStr);
	}
}

When the above program is run, the output to the console is as shown below :

str2 first appeared in str1 at index : 12

The answer is 12 because the substring "good" starts at index 12 in "hello world good morning. good day.".

h  e  l  l  o     w  o  r  l  d     g  o  o  d
0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15

2. Get the index of first occurrence of a substring – Ignore Case

In this example, we ignore the case of both the strings and try to find the occurrence of string str2 in string str1. To ignore the case, we have actually converted the strings to lowercase and then applied the function indexOf().

Please note that with the strings str1 and str2 in the below program, if you consider the case, indexOf() would return -1. But as we are ignoring the case, we got str2="GOOD" and GoOd in str1 matched.

/**
 * Java Example program to find the index of first occurrence of a substring in a string
 */
public class FirstOccurrenceExample {

	public static void main(String[] args) {
		//initialize strings
		String str1 = "hello world GoOd morning. gOOD day.";
		String str2 = "GOOD";

		//ignore case and get the index of str2 in str1
		int indexOfSubStr = str1.toLowerCase().indexOf(str2.toLowerCase());
		
		System.out.println("str2 first appeared in str1 at index : "+ indexOfSubStr);
	}
}

Run the program.

str2 first appeared in str1 at index : 12

This approach gives the index in the original string because converting to lowercase does not change the length or position of the characters in this example. For locale-sensitive text, prefer using a consistent locale when changing case.

Check whether the substring exists before using the first index

Since indexOf() returns -1 when the substring is missing, check the result before using it as an index in another operation such as substring().

</>
Copy
public class FirstOccurrenceNotFoundExample {
    public static void main(String[] args) {
        String sentence = "Java strings are immutable.";
        String search = "Python";

        int index = sentence.indexOf(search);

        if (index == -1) {
            System.out.println("Substring not found");
        } else {
            System.out.println("Substring found at index: " + index);
        }
    }
}

Output:

Substring not found

Find the first occurrence after a given index in Java

Java also provides the overloaded method indexOf(String str, int fromIndex). It starts searching from the specified index. This is useful when you want to skip an earlier match and find the next occurrence.

</>
Copy
public class IndexOfFromIndexExample {
    public static void main(String[] args) {
        String sentence = "good morning. good day.";
        String search = "good";

        int firstIndex = sentence.indexOf(search);
        int secondIndex = sentence.indexOf(search, firstIndex + search.length());

        System.out.println("First occurrence index: " + firstIndex);
        System.out.println("Second occurrence index: " + secondIndex);
    }
}

Output:

First occurrence index: 0
Second occurrence index: 14

Here, the second search starts after the first matched word. So the method returns the index of the next "good".

Common mistakes with Java indexOf() first occurrence search

  • Forgetting that indexes start from zero: If indexOf() returns 12, the match starts at the thirteenth character position.
  • Ignoring the -1 result: Always handle the case where the substring is not present.
  • Expecting case-insensitive matching: indexOf() is case-sensitive by default.
  • Passing a null substring: Do not pass null as the search string. Validate the input before calling indexOf().
  • Using the wrong starting position: When using indexOf(search, fromIndex), choose the starting index carefully so that you do not search the same occurrence again.

Java first occurrence substring search FAQs

How to get the index of first occurrence of a substring in a string using Java?

Use mainString.indexOf(searchString). It returns the zero-based index of the first occurrence of searchString in mainString. If the substring is not found, it returns -1.

What does Java indexOf() return when the substring is not found?

It returns -1. You can compare the result with -1 to check whether the substring exists in the main string.

Is String indexOf() case-sensitive in Java?

Yes. String.indexOf() is case-sensitive. To perform a simple case-insensitive search, convert both strings to the same case before calling indexOf().

How can I find the second occurrence of a substring in Java?

First find the first index using indexOf(search). Then call indexOf(search, firstIndex + search.length()) to start searching after the first match.

Can indexOf() search for a character as well as a substring?

Yes. Java String has overloaded indexOf() methods for searching a character and for searching a substring.

Editorial QA checklist for this Java indexOf() tutorial

  • Confirm that every example explains the zero-based index returned by String.indexOf().
  • Check that not-found cases clearly mention the -1 return value.
  • Ensure case-sensitive and case-insensitive searches are not mixed without explanation.
  • Verify that new code blocks use PrismJS-compatible classes such as language-java syntax or output.
  • Keep the existing Java Tutorial link unchanged.

Conclusion

In this Java Tutorial, we have learned how to get index of first occurrence of a substring in a String, by considering or ignoring the case of alphabets. Use indexOf() when you need the first matching index, check for -1 when the substring may be absent, and use the overloaded indexOf(search, fromIndex) method when you need to continue searching after a given position.