Java .indexOf()
Published May 11, 2022Updated May 13, 2022
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)
strcan be aString, or anintrepresenting a character or Unicode value. The index where this value is found will be returned.indexis 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
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours