How to use indexOf() in Java

In Java, the indexOf() function is used to find the index of a specific character or substring.

In case the function successfully locates the character or substring, the starting index is returned. If not, -1 is returned.

There are four variants of the indexOf() function. Let’s look at each of them in detail.

1. indexOf(ch)

This returns the index of the first occurrence of the character ch in the given string.

Parameter

  • ch - the character to search for

Example

svg viewer
class HelloWorld {
public static void main( String args[] ) {
String str = "Hello!";
System.out.printf("o is located at index: %d", str.indexOf('o'));
}
}

2. indexOf(ch, searchFrom)

This variant of the indexOf() function searches for the first occurrence of the character ch starting from the specified index, searchFrom, of the string.

Parameter

  • ch - the character to search for
  • searchFrom - the index where the search will begin from

Example

svg viewer
class HelloWorld {
public static void main( String args[] ) {
String str = "Hello!";
System.out.printf("l is located at index: %d", str.indexOf('l',3));
}
}

3. indexOf(str)

This variant of the indexOf() function returns the index at which the first occurrence of the String str starts.

Parameter

  • str - the string to search for

Example

svg viewer
class HelloWorld {
public static void main( String args[] ) {
String str = "Image!";
System.out.printf("age is located at index: %d", str.indexOf("age"));
}
}

4. indexOf(str, searchFrom)

This variant of the indexOf() function returns the starting index of the first occurrence of the String str, starting the search from the specified index, searchFrom, of the string.

Parameter

  • str - the string to search for
  • searchFrom - the index where the search will begin from

Example

svg viewer

As the substring age is not located ahead of the third index, the function will return -1.

class HelloWorld {
public static void main( String args[] ) {
String str = "Image!";
System.out.printf("age is located at index: %d", str.indexOf("age", 3));
}
}
Copyright ©2024 Educative, Inc. All rights reserved