View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

charAt() in Java: Syntax, Examples, and Common Errors

Updated on 28/04/20256,044 Views

Accessing individual characters is a common task when working with strings in Java. The charAt() function in Java programming helps retrieve a character at a specific index within a string. It is crucial in string manipulation, validation, and character-based operations. Understanding how charAt() works, its syntax, examples, and common errors like StringIndexOutOfBoundsException is essential for writing efficient Java programs. This guide will cover all technical aspects of the charAt() in Java with examples.

Take your Java expertise to the next level — enroll in upGrad’s Software Engineering course now!

Definition and Usage of charAt() in Java

The charAt() method in Java returns the character located within a string's specified index. It’s zero-indexed, meaning the first character is at index 0, the second at index 1, and so on.

Key Points:

  • It belongs to the String class.
  • It returns a char value.
  • If the index is invalid (less than 0 or greater than string length - 1), it throws StringIndexOutOfBoundsException.

Syntax

char character = string.charAt(index);

Must read: Top 13 String Functions in Java | Java String [With Examples]

Parameters:

  • index — the position of the character you want to retrieve (starting from 0).

Returns:

  • The character at the specified position.

Throws:

  • StringIndexOutOfBoundsException if the index is out of range.

Step into the future of tech with these top-rated software engineering courses:

StringIndexOutOfBoundsException Error

The StringIndexOutOfBoundsException occurs when you try to access a character at an invalid index —

For example, using an index less than 0 or greater than or equal to the string’s length.Always validate the index or use try-catch blocks to avoid this error during runtime.

public class Main {
    public static void main(String[] args) {
        String str = "Hello";
        try {
            System.out.println(str.charAt(8)); // Invalid index
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}

Output:

Caught Exception: String index out of range: 8

Explanation:

In the above code, the string "Hello" has a length of 5 (indices 0–4).

Trying to access str.charAt(8) causes StringIndexOutOfBoundsException, as 8 is beyond the string’s limit.

The exception is caught and a meaningful message is printed instead of crashing the program.

Also read: Difference Between char and String in Java

5 Java charAt() Examples

Here are simple, real-world examples showing how charAt() in Java works:

1. Accessing the First Character

public class Main {
    public static void main(String[] args) {
        String text = "Java";
        char firstChar = text.charAt(0);
        System.out.println(firstChar);
    }
}

Output: 

J

Explanation:

The code fetches the character at index 0 of "Java", which is 'J'. Indexing starts from 0 in Java strings.

Must check: String Length in Java

2. Accessing the Last Character

public class Main {
    public static void main(String[] args) {
        String word = "Programming";
        char lastChar = word.charAt(word.length() - 1);
        System.out.println(lastChar);
    }
}

Output:

g

Explanation:

Using word.length() - 1 dynamically fetches the last character 'g' of "Programming", ensuring safe access.

Checkout: Comprehensive Guide to Exception Handling in Java: Best Practices and Examples

3. Iterating Each Character of a String

public class Main {
    public static void main(String[] args) {
        String str = "Code";
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
        }
    }
}

Output:

C

o

d

e

Explanation: The loop prints each character one by one. charAt(i) accesses the character at the current loop index.

Must Read: Char Array in Java

4. Checking for a Specific Character

public class Main {
    public static void main(String[] args) {
        String data = "StackOverflow";
        if (data.charAt(5) == 'O') {
            System.out.println("Character at index 5 is O");
        } else {
            System.out.println("Different character found");
        }
    }
}

Output:

Character at index 5 is O

Explanation: The program checks if the character at index 5 of "StackOverflow" is 'O' and confirms it with a message.

Also read: Reverse String in Java

5. Handling Exception for Invalid Index

public class Main {
    public static void main(String[] args) {
        String message = "Hello";
        try {
            char ch = message.charAt(10); // Invalid index
            System.out.println(ch);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("Index is out of range!");
        }
    }
}

Output:

Index is out of range!

Explanation: Since "Hello" has only 5 characters (index 0–4), accessing index 10 throws an exception, which is caught and handled.

Final Thoughts

The charAt() method in Java is fundamental for any operation where character-level string processing is needed. Whether you are validating user inputs, parsing texts, or developing algorithms, mastering charAt() will greatly simplify your coding and avoid common pitfalls like invalid index errors.

FAQs

1. How does the charAt() method work in Java?

The charAt() method retrieves the character located at a specific index in a string. Indexing starts from 0. If you provide a valid index, it returns the corresponding character; if the index is invalid, Java throws a StringIndexOutOfBoundsException.

2. What happens if I give a negative index to charAt()?

If you pass a negative index to the charAt() method, Java throws a StringIndexOutOfBoundsException. This is because string indices must always be within the range from 0 to the length of the string minus one.

3. Can charAt() be used in a for loop?

Yes, charAt() is commonly used inside a for loop to iterate over each character in a string. You can access each character by incrementing the index value from 0 up to the string’s length minus one.

4. Is charAt() zero-based indexing in Java?

Yes, Java uses zero-based indexing for strings. This means the first character of the string is at index 0, the second character at index 1, and so on until string.length() - 1.

5. What exception is thrown by charAt() when an invalid index is accessed?

The charAt() method throws a StringIndexOutOfBoundsException when you try to access a character at an index that is either negative or greater than or equal to the string’s length.

6. Can we use charAt() with an empty string?

No, using charAt() on an empty string will immediately throw a StringIndexOutOfBoundsException, even if you try to access index 0, because an empty string has no characters to retrieve.

7. How to safely use charAt() without causing exceptions?

To avoid exceptions, always check that the index is greater than or equal to 0 and less than the string's length. You can use conditions like if (index >= 0 && index < string.length()) before calling charAt().

8. Can charAt() return a number?

The charAt() method returns a char, which represents a single character, not a numeric value. However, since characters have Unicode values, you can cast the result to an integer to get its numeric representation.

9. How is charAt() different from substring()?

The charAt() method returns a single character at a specified index, while substring() extracts a sequence of characters between a starting and ending index, returning a new string instead of a single character.

10. Can charAt() be used to reverse a string?

Yes, you can use charAt() inside a loop that runs backward (from last index to 0) to manually build a reversed version of the string by accessing each character one by one.

11. Can we chain multiple charAt() calls?

No, charAt() returns a char, not another String. Since a char is a primitive type, you cannot chain charAt() methods directly like you can with string methods. You must operate on the original string again.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.