Home »
Java programming language
Java String indexOf(int ch) Method with Example
Java String indexOf(int ch) Method: Here, we are going to learn about the indexOf(int ch) method with example in Java.
Submitted by IncludeHelp, on February 20, 2019
String indexOf(int ch) Method
indexOf(int ch) is a String method in Java and it is used to get the index of a specified character in the string.
If the character exists in the string, it returns the index of the first occurrence of the character, if the character does not exist in the string, it returns -1.
Syntax:
int str_object.indexOf(int chr);
Here,
- str_object is an object of main string in which we have to find the index of given character.
- chr is a character to be found in the string.
It accepts a character and returns an index of its first occurrence or -1 if the character does not exist in the string.
Example:
Input:
String str = "IncludeHelp"
Function call:
str.indexOf('H')
Output:
7
Input:
String str = "IncludeHelp"
Function call:
str.indexOf('W')
Output:
-1
Java code to demonstrate the example of String.indexOf() method
public class Main
{
public static void main(String[] args) {
String str = "IncludeHelp";
char ch;
int index;
ch = 'H';
index = str.indexOf(ch);
if(index != -1)
System.out.println(ch + " is found at " + index + " position.");
else
System.out.println(ch + " does not found.");
ch = 'e';
index = str.indexOf(ch);
if(index != -1)
System.out.println(ch + " is found at " + index + " position.");
else
System.out.println(ch + " does not found.");
ch = 'W';
index = str.indexOf(ch);
if(index != -1)
System.out.println(ch + " is found at " + index + " position.");
else
System.out.println(ch + " does not found.");
}
}
Output
H is found at 7 position.
e is found at 6 position.
W does not found.