.indexOf()
Published May 11, 2022Updated May 13, 2022
Contribute to Docs
The .indexOf()
method returns the zero-indexed position of the first occurrence of the given character(s) in a string. It returns -1
if the given characters(s) are not found.
Syntax
string.indexOf(str, index)
str
can be aString
, or anint
representing a character or Unicode value. The index where this value is found will be returned.index
is an optional index position in the string to start the search from.
Example
The following example finds the position of the string “World” in “Hello World!”:
class FindIndex {public static void main(String[] args) {String greeting = "Hello World!";System.out.println(greeting.indexOf("World"));}}
This outputs the following:
6
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours