Java String indexOf()

Last Updated On Thursday 30th Jun 2022

index of java

The indexOf() method returns the index of the first occurrence of the specified character within the string.

Syntax

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

Parameters

  • ch – int value
  • str – string whose starting index
  • fromIndex (optional) – starting from this index

Returns

  • returns the index of the first occurrence of the specified character/string
  • returns -1 if the specified character/string is not found.

java index

	class Main {
  public static void main(String[] args) {
      String myStr = "Hello World";
      System.out.println(myStr.indexOf("World"));
  }
}
	

Output

	6
	
  • The World string is in the Hello World string and returns the index 6.
	public class Main {
  public static void main(String[] args) {
    String myStr = "CodeJagd";
    System.out.println(myStr.indexOf("C"));
    System.out.println(myStr.indexOf("d"));
    System.out.println(myStr.indexOf("d", 4));
  }
}
	

Output

	0
2
7
	
  • The character d occurs two times in the CodeJagd string. The indexOf() method returns the index of the first occurrence of d.
  • The d letter is in the CodeJagd string. However, myStr.indexOf("d", 4) returns 7 instead of 2. It is because the search starts at index 4.
indexof java
java indexof
indexof in java
java string indexof