0
0
JavaHow-ToBeginner · 3 min read

How to Find Index of Character in String Java - Simple Guide

In Java, you can find the index of a character in a string using the indexOf() method. It returns the position of the first occurrence of the character or -1 if the character is not found.
📐

Syntax

The indexOf() method is called on a string object and takes a character as an argument. It returns an int representing the index position of the first occurrence of that character.

  • string.indexOf(char): Finds the first index of char.
  • Returns -1 if the character is not found.
java
int index = string.indexOf('a');
💻

Example

This example shows how to find the index of the character 'a' in a string. It prints the index if found or a message if not found.

java
public class FindCharIndex {
    public static void main(String[] args) {
        String text = "Java programming";
        char target = 'a';
        int index = text.indexOf(target);

        if (index != -1) {
            System.out.println("Character '" + target + "' found at index: " + index);
        } else {
            System.out.println("Character '" + target + "' not found in the string.");
        }
    }
}
Output
Character 'a' found at index: 1
⚠️

Common Pitfalls

One common mistake is expecting indexOf() to return the position of all occurrences or to work with strings instead of characters without proper overload. Also, remember that indexing starts at 0, so the first character is at index 0.

If you want to find the index of a substring, you can pass a string instead of a character.

java
public class PitfallExample {
    public static void main(String[] args) {
        String text = "banana";

        // Wrong: expecting all indexes
        int firstIndex = text.indexOf('a');
        System.out.println("First 'a' at: " + firstIndex); // prints 1

        // Correct: to find all indexes, loop is needed
        System.out.print("All 'a' positions: ");
        int index = text.indexOf('a');
        while (index >= 0) {
            System.out.print(index + " ");
            index = text.indexOf('a', index + 1);
        }
    }
}
Output
First 'a' at: 1 All 'a' positions: 1 3 5
📊

Quick Reference

  • string.indexOf(char): Returns first index of character or -1 if not found.
  • string.indexOf(char, fromIndex): Starts search from fromIndex.
  • Indexing starts at 0.

Key Takeaways

Use indexOf() to find the first position of a character in a string.
If the character is not found, indexOf() returns -1.
Index counting starts at 0, so the first character is at index 0.
To find multiple occurrences, use a loop with indexOf(char, fromIndex).
You can also search for substrings using indexOf(String).