Open In App

Java String indexOf() Method

Last Updated : 19 Nov, 2024
Suggest changes
Share
Like Article
Like
Report

In Java, the String indexOf() method returns the position of the first occurrence of the specified character or string in a specified string. In this article, we will learn various ways to use indexOf() in Java.

Example:

Below is the simplest way that returns the index of the first occurrence of a specified character in a string, or -1 if the character does not occur.

Java
// Java code to demonstrate the working of String indexOf() // using indexOf(char ch) public class Index1 {    public static void main(String args[]) {    String s = new String("Welcome to geeksforgeeks");  System.out.print("Found g first at position: ");  System.out.println(s.indexOf('g'));  } } 

Output
Found g first at position: 11 

Explanation:

In the above example, it finds the first occurrence of the character g in the string "Welcome to geeksforgeeks" and prints its index i.e. 11.

Different Variants of indexOf() Method in Java

There are 3 variants of the indexOf() method are mentioned below:

1. indexOf(char ch, int strt) 

This method returns the index of the first occurrence of the specified character by starting the search at the specified index.

Example:

Java
// Java code to demonstrate the working of String indexOf(char ch, int strt) public class Index2 {    public static void main(String args[]) {    String s = new String("Welcome to geeksforgeeks");  System.out.print(  "Found g after 13th index at position: ");  System.out.println(s.indexOf('g', 13));  } } 

Output
Found g after 13th index at position: 19 


2. indexOf(String str) 

This method returns the index of the first occurrence of the specified substring in the string.

Example:

Java
// Java code to demonstrate the working of String indexOf(String str) public class Index3 {    public static void main(String args[]) {    String s = new String("Welcome to geeksforgeeks");  // Initializing search string  String s1 = new String("geeks");  // print the index of initial character of Substring  System.out.print(  "Found geeks starting at position: ");  System.out.print(s.indexOf(s1));  } } 

Output
Found geeks starting at position: 11


3. indexOf(String str, int strt) 

This method returns the index of the first occurrence of the specified substring by starting the search at the specified index.

Example:

Java
// Java code to demonstrate the working of String indexOf(String str, int strt) public class Index4 {    public static void main(String args[]) {  String s = new String("Welcome to geeksforgeeks");  // Initializing search string  String s1 = new String("geeks");  // print the index of initial character  // of Substring after 14th position  System.out.print(  "Found geeks(after 14th index) starting at position: ");  System.out.print(s.indexOf(s1, 14));  } } 

Output
Found geeks(after 14th index) starting at position: 19



Similar Reads