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.


string.indexOf(str, index)
  • str can be a String, or an int 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.


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!";

This outputs the following:


All contributors

Looking to contribute?

Learn Java on Codecademy