Java String indexOf()

Learn to find the location of a character or substring in a given string, using the String.indexOf() method. The indexOf() is a standard approach for finding the substrings, and indexOf() method is available in almost all programming languages.

If we do not want the location of the substring and are only interested in verifying if the substring is present, then consider using String.contains() API.

1. String.indexOf() API

The String.indexOf() in Java returns the index location of a specified character or string. The indexOf() method is an overloaded method and accepts two arguments:

  • substring or ch: the substring that needs to be located in the current string.
  • fromIndex: the start position where the search begins in the current string.
int indexOf(String substring)
int indexOf(String substring, int fromIndex)

int indexOf(int ch)
int indexOf(int ch, int fromIndex)

If the argument character or substring is not found in the string, the method returns -1.

2. String.indexOf() Example

Let us see a few examples to understand the indexOf() better.

2.1. Find Substring Location

In the following example, we check if the substring “World” exists in the given string. If it exists, at what index is the substring present?

Java String.indexOf()

The substring is found at the index position 6, and the indexOf() method returns 6.

String str = "Hello World";

Assertions.assertEquals(6, str.indexOf("World"));

2.2. Find Substring From Index

There may be cases when we want to locate a substring but only after a certain number of characters. In such cases, we can pass the second argument fromIndex that skips the specified number of characters and then starts searching from the substring or the character.

In the following example, the character ‘o’ is present at index positions 4 and 7. Let us assume that we have to skip the first 5 characters, and then only we can search for the character ‘o’.

As expected, the indexOf() method returns 7 because that is the first occurrence of the character ‘o’ after the index position 5.

Assertions.assertEquals(7, str.indexOf('o', 5));

3. NULL is Not Allowed

Passing the null argument is not allowed, and It will result in NullPointerException.

Assertions.assertThrows(NullPointerException.class, () -> {

Happy Learning !!

Reference: Java String Doc

Sourcecode on Github


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode