Java String lastIndexOf() Method Example

1. Introduction

The String.lastIndexOf() method in Java is used to find the index of the last 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 lastIndexOf() method to locate characters and substrings within a string, starting from the end.

Key Points

- lastIndexOf() returns the index of the last occurrence of a specified character or substring.

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

- Overloaded versions of lastIndexOf() allow specifying a starting point for the search.

2. Program Steps

1. Declare a string.

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

3. Print the indices.

3. Code Program

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

Output:

Last index of 'e': 48
Last index of 'welcome': 36

Explanation:

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

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

3. int indexSubstring = str.lastIndexOf("welcome"): Finds the index of the last occurrence of the substring "welcome" in str.

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

5. System.out.println("Last index of 'welcome': " + indexSubstring): Prints the index of the last occurrence of "welcome".


Comments