indexOf() :

 In Java, the indexOf() method is a part of the String class and is used to find the index of a specified substring or character within a string.

 It returns the index of the first occurrence of the specified substring or character in the string, or -1 if the substring or character is not found.


The general syntax of the indexOf() method is:


public int indexOf(String str) ;
public int indexOf(String str, int fromIndex);
public int indexOf(char ch) ;
public int indexOf(char ch, int fromIndex);

Here's an explanation of how the indexOf() method works:


indexOf(String str):


This form of the method searches for the first occurrence of the specified str substring within the string.

It returns the index of the first character of the found substring, or -1 if the substring is not found.

indexOf(String str, int fromIndex):


This form of the method searches for the first occurrence of the specified str substring within the string, starting from the fromIndex position.

It returns the index of the first character of the found substring, or -1 if the substring is not found.

The search starts from the fromIndex position and continues towards the end of the string.

indexOf(char ch):


This form of the method searches for the first occurrence of the specified character ch within the string.

It returns the index of the first occurrence of the character, or -1 if the character is not found.


indexOf(char ch, int fromIndex):

This form of the method searches for the first occurrence of the specified character ch within the string, starting from the fromIndex position.

It returns the index of the first occurrence of the character, or -1 if the character is not found.

The search starts from the fromIndex position and continues towards the end of the string.

Here are a few examples to illustrate the usage of the indexOf() method:


String str = "Hello, World!"
int index1 = str.indexOf("o"); 
System.out.println(index1); // Output: 4 
int index2 = str.indexOf("o", 5); 
System.out.println(index2); // Output: 8 
int index3 = str.indexOf("Java");
 System.out.println(index3); // Output: -1 
int index4 = str.indexOf('W'); 
System.out.println(index4); // Output: 7

In the above examples:


indexOf("o") finds the first occurrence of the substring "o" in the string and returns the index 4.

indexOf("o", 5) starts searching for the substring "o" from index 5 and finds the next occurrence at index 8.

indexOf("Java") tries to find the substring "Java" in the string, but since it is not present, it returns -1.

indexOf('W') finds the first occurrence of the character 'W' in the string and returns the index 7.

The indexOf() method is commonly used to locate the position of substrings or characters within a string, allowing you to perform various string manipulation and search operations in Java.