Java indexOf() Method Explained

In Java, the indexOf() function is used to search for the first occurrence of a specified string or character in a string. Here are some common uses of the indexOf() function:

  1. Use the indexOf(String str) method: this method is used to find the first occurrence of a specific string within another string. If no matching substring is found, it returns -1. Example:
  2. string = “Hello, World!”;
    position = string.indexOf(“World”);
    System.out.println(position); // Output: 7
  3. Using the indexOf(int ch) method: this method is used to find the first occurrence of a specified character in the string. Example:
  4. Create a string variable with the value “Hello, World!”. Find the index of the first occurrence of the character ‘o’ in the string and print it, which will output 4.
  5. With the indexOf(String str, int fromIndex) method, you can search for a specified substring starting at a specified index position. Example:
  6. The string variable ‘str’ contains the value “Hello, World!”.
    We are searching for the first occurrence of the letter “l” starting from index 3 in the string.
    The result index is 3.
    Print the output.

By using the above method, you can utilize the indexOf() function in Java to find the position index of a specified string or character within another string.

bannerAds