0
0
JavaHow-ToBeginner · 3 min read

How to Use charAt in Java: Simple Guide with Examples

In Java, use the charAt(int index) method on a string to get the character at the specified index. The index starts at 0, so charAt(0) returns the first character of the string.
📐

Syntax

The charAt method is called on a string object and takes one parameter:

  • index: an integer representing the position of the character you want, starting from 0.

It returns the character at that position as a char type.

java
char ch = string.charAt(index);
💻

Example

This example shows how to get characters from a string using charAt and print them.

java
public class CharAtExample {
    public static void main(String[] args) {
        String word = "Hello";
        char firstChar = word.charAt(0); // 'H'
        char thirdChar = word.charAt(2); // 'l'

        System.out.println("First character: " + firstChar);
        System.out.println("Third character: " + thirdChar);
    }
}
Output
First character: H Third character: l
⚠️

Common Pitfalls

Common mistakes when using charAt include:

  • Using an index that is negative or greater than or equal to the string length, which causes StringIndexOutOfBoundsException.
  • Forgetting that string indexes start at 0, so charAt(1) is the second character, not the first.

Always check the string length before calling charAt to avoid errors.

java
public class CharAtPitfall {
    public static void main(String[] args) {
        String text = "Java";
        // Wrong: index 4 is out of bounds (valid indexes: 0 to 3)
        // char ch = text.charAt(4); // This throws StringIndexOutOfBoundsException

        // Right: check length before accessing
        int index = 4;
        if (index >= 0 && index < text.length()) {
            char ch = text.charAt(index);
            System.out.println(ch);
        } else {
            System.out.println("Index out of range");
        }
    }
}
Output
Index out of range
📊

Quick Reference

MethodDescription
charAt(int index)Returns the character at the specified index (0-based)
length()Returns the length of the string
index >= 0 && index < length()Valid index range to avoid errors

Key Takeaways

Use charAt(index) to get the character at position index in a string, starting from 0.
Always ensure the index is within 0 and string length - 1 to avoid errors.
charAt returns a char, which can be stored or printed directly.
Remember string indexes start at 0, so the first character is at index 0.
Check string length before using charAt to prevent exceptions.