Java Tutorial



Java Tutorial

charAt() in Java


Welcome to this tutorial on charAt() in Java. This comprehensive guide aims to walk you through the fundamentals and advanced usage of `charAt()`, enabling you to harness the power of character-level operations on strings.

We will look into charAt() in Java examples and learn how to retrieve characters by index, handle edge cases, and apply this knowledge to solve real-world programming challenges. 


The charAt() in Java is useful for manipulating and extracting individual characters from a string. Strings are essential data types in any programming language since they enable you to interact with text-based data in your programs. Double quotation marks ("") are used to encapsulate strings in Java.

Using charAt() in Java is a handy method for extracting certain characters from a string in Java programming. This technique lets you access certain characters inside a string depending on their index locations. The charAt() function comes in handy whether you're looking for a specific character or need to carry out character-based activities. 

Java's charAt() function retrieves the character's char value from a string at the provided or given index. The index value must be in the range of 0 and length()-1. The initial character's index is 0, followed by character number one, and so on.

charAt() in Java Syntax

Here is the syntax for using the charAt() method:

char charAt(int index)

  • int index: The character index to be retrieved from the string. The index is zero-based, so the first character is at index 0, the second is at index 1, and so on.

  • char: The character at the specified index in the string.

The charAt() method is a member of the String class, so you need to call it on an instance of the String class. It takes an integer parameter index, which represents the character's position you want to retrieve.

For example:


We would use the above syntax to retrieve the 6th character from a string.

Now, let us check out a working example:

public class upGradTutorials {
    public static void main(String[] args) {
        String str = "upGrad.";
        char result = str.charAt(3);
        System.out.println(result);  // Output: r

In the main method, we declare a String variable str and assign it the value "upGrad.". Then we use the charAt() method to retrieve the character at index 7, 'r', and store it in the result variable. Finally, we print the value of result to the console, which will output 'r'.

Example of charAt() in Java

Reverse a String

public class upGradTutorials {
    public static void main(String[] args) 
        String str = "upGrad teaches Java.";
        StringBuilder reversed = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {

In the above program, we have a string "upGrad teaches Java.". We create a StringBuilder object called reversed to store the reversed string. We iterate over the characters of the original string starting from the last character (index str.length() - 1) to the first character (index 0). We use the charAt() method to retrieve each character and append it to the reversed StringBuilder. Finally, we convert the StringBuilder to a String using the toString() method and print the reversed string to the console.

Check if a String is Palindrome

(When using string "level" while running the program)
(When using string "upGrad" while running the program)
public class upGradTutorials {
    public static void main(String[] args) {
        String str = "upGrad";
        boolean isPalindrome = true;
        int left = 0;
        int right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                isPalindrome = false;
        if (isPalindrome) {
            System.out.println("The string is a palindrome.");
        } else {
            System.out.println("The string is not a palindrome.");

In the above example, we have a string "upGrad". We use two pointers, left and right, that point to the first and last characters of the string, respectively. We compare the characters at these pointers using the charAt() method. If they are not equal, we set the isPalindrome flag to false and exit the loop.

The loop continues until the left pointer becomes greater than or equal to the right pointer. After the loop, we check the value of the isPalindrome flag. If it is true, we print that the string is a palindrome; otherwise, we print that the string is not a palindrome.

Count Occurrences of a Character in a String

public class upGradTutorials {
    public static void main(String[] args) {
        String str = "Hello, world!";
        char target = 'o';
        int count = 0;

        int index = -1;
        while ((index = str.indexOf(target, index + 1)) != -1) {

        System.out.println("Number of occurrences of '" + target + "': " + count);

In this example, we have a string "Hello, world!" and a target character 'o'. We initialize a count variable to keep track of the number of occurrences. We also initialize the index variable to -1. We use the indexOf() method of the string to find the index of the target character starting from the index + 1 position. If a match is found, the index is updated, and we increment the count.

The loop continues until no more occurrences are found (i.e., indexOf() returns -1). Finally, we print the count of occurrences to the console.

Exceptions of charAt() in Java

An IndexOutOfBoundsException exception is thrown if the specified index is negative or greater than or equal to the length of the string. This exception indicates that the index is out of the valid range of the string.

It is essential to handle this exception when using the charAt() method to ensure your code does not crash or produce unexpected results when accessing characters at invalid indices.

Here is an example where we use a try-catch block to handle the IndexOutOfBoundsException when using charAt():

public class upGradTutorials {
    public static void main(String[] args) {
        String str = "Hello";
        try {
            char result = str.charAt(10);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Invalid index. Exception: " + e.getMessage());

In the above program, we attempt to access the character at index 10 in the string "Hello". Since the string has a length of 5, the index is out of bounds and triggers an IndexOutOfBoundsException. The catch block catches the exception, and we print a custom error message to the console, including the details of the exception.

By handling the IndexOutOfBoundsException, we ensure that our program handles invalid index scenarios gracefully and avoids unexpected crashes or errors.

charAt() in Java for loop

public class upGradTutorials {
    public static void main(String[] args) {
        String sentence = "upGrad teaches Java programming.";
        int vowelCount = 0;
        int consonantCount = 0;
        for (int i = 0; i < sentence.length(); i++) {
            char c = sentence.charAt(i);
            // Check if the character is a letter
            if (Character.isLetter(c)) {
                // Check if the character is a vowel
                if (isVowel(c)) {
                } else {
        System.out.println("Number of vowels: " + vowelCount);
        System.out.println("Number of consonants: " + consonantCount);
    private static boolean isVowel(char c) {
        c = Character.toLowerCase(c);
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';

In this example, we have a sentence "upGrad teaches Java programming." We iterate over each character in the sentence using a for loop and use the charAt() method to retrieve each character at its corresponding index.

Inside the loop, we first check if the character is a letter using Character.isLetter(c). If it is, we then call the isVowel() method to determine whether the character is a vowel or a consonant. If it's a vowel, we increment the vowelCount variable; otherwise, we increment the consonantCount variable.

After the loop finishes, we print the total number of vowels and consonants in the sentence to the console.

The isVowel() method is a helper method that checks whether a given character is a vowel. It converts the character to lowercase and then compares it against the vowels 'a', 'e', 'i', 'o', and 'u'. If the character matches any of these vowels, the method returns true; otherwise, it returns false.


We have discussed the essential concepts and examples of Java's charAt() function in this tutorial. It is important to practice using the charAt() function in various contexts, including extracting substrings, verifying user input, and creating original algorithms. This will improve your knowledge and ability to use this fundamental yet crucial Java method.


1. What is the maximum value for an input in charAt() function in Java?

The maximum value for an input in charAt() in Java is the numerical equivalent of the number of characters in a string - 1. The charAt() function starts counting from 0, not 1.  

2. What is charAt(0) in Java?

charAt(0) has no specified or constant value in Java. However, it returns the 0th character of a string, which means the first character. 

3. What is charAt equals in Java?

The equals() method in Java's Character class compares two Character objects. It takes one Character object as input and compares it with another Character object. Henceforth, it returns a boolean value indicating whether they are equal.

4. What is ASCII?

The American Standard Code for Information Interchange is an index for assigning numerical values to alphabet characters. They are divided into two sections- capital and small.

Leave a Reply

Your email address will not be published. Required fields are marked *