Finding the Index of the Second Character in a Java String

In Java development, retrieving the index of the second character in a string is a common task that involves basic string operations and index manipulation. This article demonstrates how to accomplish this using standard Java methods, with a focus on charAt() and indexOf().

To locate the second character, you first verify that the string contains atleast two characters. The second character resides at index 1 (zero-based indexing). You can extract it with charAt(1) and then find its first occurrence using indexOf(). Note that indexOf() returns the earliest index of the given character, which in a non‑duplicate scenario will be the same as the extracted position.

Below is a complete Java example:

public class SecondCharIndex {
    public static void main(String[] args) {
        String text = "Hello";

        if (text.length() >= 2) {
            char secondChar = text.charAt(1);
            int index = text.indexOf(secondChar);
            System.out.println("Index of the second character: " + index);
        } else {
            System.out.println("String is too short to contain a second character.");
        }
    }
}

When executed, the program outputs Index of the second character: 1. This approach works reliably when the second character is unique within the string. If duplicates exist, indexOf() returns the first occurrence, which may not be index 1—in such cases, simply using the constant 1 is more appropriate.

Tags: java String Manipulation charAt indexOf

Posted on Sun, 17 May 2026 04:36:53 +0000 by thedarkwinter