Using indexOf in Java

In Java, the String class offers the indexOf() function, which aids in locating the position of a character or a substring within the parent string. The method returns the first occurrence's position when the character or substring is found. If it remains undetected, the function returns -1. Several variants of the indexOf() method exist, enabling the user to define the target character or substring and if desired, a start index for the search. This becomes useful for refined searches, especially when multiple occurrences of a character or substring are anticipated. In this Java IndexOf Example, we pinpoint the positions of a substring's initial and subsequent appearances. Click Execute to run the Java IndexOf Example online and see the result.
Using indexOf in Java Execute
public class IndexOfDemo {
    public static void main(String[] args) {
        String str = "Hello, World! Hello, Universe!";

        int firstOccurrence = str.indexOf("Hello");
        System.out.println("First occurrence of 'Hello': " + firstOccurrence);

        int nextOccurrence = str.indexOf("Hello", firstOccurrence + 1);
        System.out.println("Next occurrence of 'Hello': " + nextOccurrence);
    }
}
Updated: Viewed: 40 times