Java String indexOf() Method Example

1. Introduction

The String.indexOf() method in Java is used to find the index of the first occurrence of a specified character or substring within a string. If the character or substring is not found, this method returns -1. This tutorial will demonstrate how to use the indexOf() method to locate characters and substrings within a string.

Key Points

- indexOf() returns the index of the first occurrence of a specified character or substring.

- If the character or substring is not found, it returns -1.

- Overloaded versions of indexOf() allow you to specify a starting point for the search.

2. Program Steps

1. Declare a string.

2. Search for a character and a substring to find their first occurrence indices.

3. Print the indices.

3. Code Program

public class StringIndexOfExample {
    public static void main(String[] args) {
        // Declare a String to search
        String str = "Hello, welcome to the world of Java!";
        // Search for the first occurrence of the character 'e'
        int indexChar = str.indexOf('e');
        // Search for the first occurrence of the substring "Java"
        int indexSubstring = str.indexOf("Java");
        // Print the results
        System.out.println("Index of 'e': " + indexChar);
        System.out.println("Index of 'Java': " + indexSubstring);
    }
}

Output:

Index of 'e': 1
Index of 'Java': 31

Explanation:

1. String str = "Hello, welcome to the world of Java!": Declares and initializes a String variable str.

2. int indexChar = str.indexOf('e'): Finds the index of the first occurrence of the character 'e' in str.

3. int indexSubstring = str.indexOf("Java"): Finds the index of the first occurrence of the substring "Java" in str.

4. System.out.println("Index of 'e': " + indexChar): Prints the index of the first occurrence of 'e'.

5. System.out.println("Index of 'Java': " + indexSubstring): Prints the index of the first occurrence of "Java".


Comments