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 theHello World
string and returns the index6
.
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 theCodeJagd
string. TheindexOf()
method returns the index of the first occurrence ofd
. - The
d
letter is in theCodeJagd
string. However,myStr.indexOf("d", 4)
returns7
instead of2
. It is because the search starts at index4
.