STRING INSTANCE METHODS

Java String indexOf() method

indexOf() searches for a character or substring in a specific String object and returns the first matching index. If nothing is found, it returns -1.

Your first indexOf() call

String tekstas = "JavaQuest";

System.out.println(tekstas.indexOf('Q'));
System.out.println(tekstas.indexOf("Quest"));
System.out.println(tekstas.indexOf("Python"));
Console output

4
4
-1

  1. tekstas stores the value JavaQuest.
  2. indexOf('Q') finds the character Q at index 4.
  3. indexOf("Quest") finds the substring's start at the same index, 4.
  4. indexOf("Python") returns -1because that substring does not exist.

Method syntax

public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)

indexOf() variants
VariantMeaning
indexOf(int ch)Finds the first occurrence of the specified character.
indexOf(int ch, int fromIndex)Searches for a character from the specified index.
indexOf(String str)Finds the first occurrence of the specified substring.
indexOf(String str, int fromIndex)Searches for a substring from the specified index.
Return typeint – the matching index or -1if not found.

Java String string indices start at 0. The first character therefore has index 0, the second has 1, and so on.

Why is indexOf() an instance method?

indexOf() is called on a specific string because the search happens inside that String object:

int indeksas = tekstas.indexOf('v');

String tekstas = "Java";

int indeksas = tekstas.indexOf('v');

System.out.println(indeksas);
Console output

2

We therefore do not write String.indexOf(...). The method needs a specific string in which to search for a character or substring.

String tekstas = "programavimas";

System.out.println(tekstas.indexOf('a'));
System.out.println(tekstas.indexOf('m'));
Console output

5
6

indexOf('a') returns the index of the first letter a . If the character occurs several times, indexOf() still returns only the first match.

String adresas = publicLessonUrl('/java/string');

System.out.println(adresas.indexOf("javaquest"));
System.out.println(adresas.indexOf("/java"));
Console output

8
20

When passed a String, the method returns where the whole substring starts. In this example, javaquest starts after https://, giving index 8.

Searching from a particular index

String tekstas = "Java Java Java";

System.out.println(tekstas.indexOf("Java"));
System.out.println(tekstas.indexOf("Java", 1));
System.out.println(tekstas.indexOf("Java", 6));
Console output

0
5
10

  1. The first Java starts at index 0.
  2. indexOf("Java", 1) starts after the first letter and finds the second Java at index 5.
  3. indexOf("Java", 6) starts even later and finds the third Java at index 10.

A missing value returns -1

String tekstas = "JavaQuest";

int indeksas = tekstas.indexOf("Python");

if (indeksas == -1) {
  System.out.println("Nerasta");
} else {
  System.out.println("Rasta indekse " + indeksas);
}
Console output

Nerasta

-1 signals that the character or substring was not found. Check this before using the index with substring(), charAt() or other methods.

indexOf() is case-sensitive

String tekstas = "JavaQuest";

System.out.println(tekstas.indexOf("Quest"));
System.out.println(tekstas.indexOf("quest"));
Console output

4
-1

Quest and quest are different because the first letter's case differs. To search without considering case, often transform both strings using toLowerCase() or toUpperCase().

The difference from contains()

String tekstas = "Mokausi Java";

System.out.println(tekstas.contains("Java"));
System.out.println(tekstas.indexOf("Java"));
Console output

true
8

contains() answers only true or false: whether the string contains the specified part. indexOf() tells you more: whether a match exists and where it starts.

Safe use with substring()

String elPastas = "[email protected]";

int eta = elPastas.indexOf('@');

if (eta != -1) {
  String vardas = elPastas.substring(0, eta);
  String domenas = elPastas.substring(eta + 1);

  System.out.println(vardas);
  System.out.println(domenas);
}
Console output

info
javaquest.lt

First, the code finds the @ character's index. Only if it is not -1does it split the string. This avoids trying to use a nonexistent position.

Searching for an empty string

String tekstas = "Java";

System.out.println(tekstas.indexOf(""));
System.out.println(tekstas.indexOf("", 2));
Console output

0
2

An empty string is found at every valid position. Therefore, indexOf("") returns 0, while indexOf("", 2) returns 2. In practice, it is usually worth checking separately whether the search string is empty.

You cannot search for a null substring

String tekstas = "Java";

System.out.println(tekstas.indexOf(null));
Result

NullPointerException

If indexOf(String str) receives null, Java cannot search for a nonexistent substring and throws NullPointerException. Before searching, check that the search text is not null.

Common mistakes

  • Forgetting that indices start at 0.
  • -1 is used as a normal index even though it means “not found”.
  • Expecting all occurrences when one call returns only the first match.
  • Overlooking that indexOf() is case-sensitive.
  • To indexOf(String) receives null value.
  • A search from fromIndex is mistaken for a search up to that index, although it actually begins there.

When should you use indexOf()?

Use indexOf()when you need to locate a character or substring. It helps validate input, split text at delimiters, find keywords and analyze URLs or email addresses. For a simple yes/no answer, an easier choice is often contains().