Explain the usage of indexOf() and lastIndexOf() methods with one example each

Explain the usage of indexOf() and lastIndexOf() methods with one example each

Answer:-

indexOf() and lastIndexOf() Methods in Java

Both methods are used to find the position (index) of characters or substrings in a String. They return the zero-based index of the match.


1. indexOf()

  • Returns the index of the first occurrence of a character or substring.
  • If not found, returns -1.

Syntax:

int indexOf(int ch)
int indexOf(String str)
int indexOf(int ch, int fromIndex)
int indexOf(String str, int fromIndex)

Example:

public class IndexOfExample {
    public static void main(String[] args) {
        String str = "Java Programming";
        int index = str.indexOf("a");
        System.out.println("First occurrence of 'a': " + index);
    }
}

Output:

First occurrence of 'a': 1

2. lastIndexOf()

  • Returns the index of the last occurrence of a character or substring.
  • If not found, returns -1.

Syntax:

int lastIndexOf(int ch)
int lastIndexOf(String str)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str, int fromIndex)

Example:

public class LastIndexOfExample {
    public static void main(String[] args) {
        String str = "Java Programming";
        int index = str.lastIndexOf("a");
        System.out.println("Last occurrence of 'a': " + index);
    }
}

Output:

Last occurrence of 'a': 3

Summary

MethodDescriptionReturns
indexOf()Index of first matchFirst match index or -1
lastIndexOf()Index of last matchLast match index or -1

Leave a Reply

Your email address will not be published. Required fields are marked *