Java indexOf with 2 examples to search strings

The indexOf method of Java string

The indexOf is a String class method in Java. The indexOf method searches in a string by a given search term.

A few points about the indexOf Java string are:

  • The indexOf method searches from left to right for the given string.
  • If search string is found, the method will return the index number of the first occurrence.
  • If search string is not found the indexOf method will return -1.
  • The indexOf method is case sensitive, so uppercase and lowercase letters will be treated separately.
  • The index starts at zero.
Have a look at an indexOf example online

Syntax of indexOf method

The syntax to use the indexOf method is:

Strex.indexof(“search string”);

Where Strex is a string object.

Example of using Java string indexOf method

In the following example, we will use the Java indexOf method to search the whole string.


The output will be:

Index found at:25

Index found at:-1

Example of using indexOf for limited string

The example below uses Java indexOf method. This method will take two parameters.

  1. The Search term
  2. int fromindex (specifies where to start the search from, in the given string)
Experience this online


The output will be:

Index found at:25

Index found at:-1

In the example, you can see a string object is created with a sentence. After that, we used the indexOf method on that string object twice. In the first line, it started the search from 20th number while in the second line we used 26th number character to start the search in the given string.

Also see – Java strings

Was this article helpful?

Related Articles

Leave A Comment?