Home >>Java String Methods >Java String indexOf() Method

Java String indexOf() Method

Java String indexOf() Method

The indexOf() method in Java String is used to returns the position of the first occurrence of specified character in a string.

Syntax

There are four types of indexOf() methods:

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

Parameter

str - This parameter is used to represents A String value, to search for

fromIndex - This parameter is used to represents An int value of the index position to start the search from

Char - This parameter is used to represents An int value of a single character, e.g 'A', or a Unicode value

Technical Details

Returns - It is used to return An int value which represents the index of the first occurrence of the character in the string, or -1 if it never occurs

Java String indexOf() Method Example 1


public class MyClass 
{
  public static void main(String[] args) 
  {
    String myStrln1 = "Education breeds confidence, Confidence breeds Hope, Hope breeds peace.";
    System.out.println(myStrln1.indexOf("breeds"));
  }
}

Output: 10

Java String indexOf() Method Example 2


public class MyClass
{  
    public static void main(String[] args) 
	{      
        String n1 = "This is the best learning platform";         
        int index = n1.indexOf("learning", 10);  
        System.out.println("index of substring "+index);  
        index = n1.indexOf("learning", 20); 
        System.out.println("index of substring "+index);          
    }  
}  

Output: index of substring 17
index of substring -1

No Sidebar ads