Java String charAt() example

In this guide, you will learn about the String charAt() method in Java programming and how to use it with an example.

1. String charAt() Method Overview

Definition:

The charAt() method in Java's String class returns the character at the specified index of a given string.

Syntax:

str.charAt(int index)

Parameters:

- index: The zero-based index of the character to retrieve from the string.

Key Points:

- The charAt() method belongs to the String class.

- The index is zero-based, meaning the first character is at index 0, the second at index 1, and so forth.

- If you provide an index that's out of bounds (negative or greater than or equal to the string's length), a StringIndexOutOfBoundsException is thrown.

- This method is especially handy for character-by-character string parsing or operations.

2. String charAt() Method Example

public class CharAtExample {
    public static void main(String[] args) {
        String phrase = "Java Programming";

        // Retrieve the 5th character of the string
        char fifthCharacter = phrase.charAt(4);
        System.out.println("The 5th character is: " + fifthCharacter);

        // Attempt to retrieve a character beyond the string's length
        try {
            char outOfBoundsCharacter = phrase.charAt(50);
            System.out.println("Character: " + outOfBoundsCharacter);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("Error: Index out of bounds.");
        }
    }
}

Output:

The 5th character is: a
Error: Index out of bounds.

Explanation:

In our example, we first extract the 5th character (index 4) of the string "Java Programming", which is the letter 'a'. 

Next, we purposefully try to extract a character using an out-of-bounds index. This throws a StringIndexOutOfBoundsException, which we catch and print an error message.

Related Java String Class method examples

Comments