Java String charAt() Method with Examples

This article explores the charAt() method, an integral inbuilt function in the Java programming language. Without a preamble, we delve into its necessity, advantages, and syntax, aiming for a direct and comprehensive understanding.

Additionally, the article concludes with practical examples of the charAt() method in action, encouraging readers to enhance their grasp by actively practising and experimenting with the provided code. To expedite mastery, readers are encouraged to engage in hands-on exploration, making modifications and considering diverse scenarios for a more thorough comprehension of the charAt() method.

What does the charAt() method In Java do?

The method retrieves the character at the specified index in a string. For instance, if you have a string called and you call, the method will return the character. If you call, the method will return the character. The index of the first character in a string is 0, the index of the second character is 1, and so on.

Since StringBuffer is similar to String (but mutable), indexing is also similar. Note that indexing always starts from 0, this means that the first char value is at index 0, the next at index 1, and so on, as in String/Array indexing. Thus the Indexing ranges from 0 to n-1, where n is the length of the string.

In addition, if the character value specified by the index is a surrogate pair, the surrogate value is returned. This means that if the character value is a combination of two code points, the surrogate pair is returned instead of the individual code points. This is important because it allows for the correct representation of characters in Unicode.

What is the syntax of using the charAt() method in Java?

Before proceeding to the examples that use the charAt() method, let us take a look at the syntax of this method, and discuss the fields present in it. Below is the syntax of the charAt() method in Java:

charAt(index)

You can pass the index value of the character you want to obtain as the parameter of the charAt() method. The return value of this method is of the datatype char and returns the character that is present at the index value specified in the parameter list.

You must note that if the index you entered is greater than or equal to the length of the string, you will get an Index out-of-bound error. Thus, you must always specify an index value ranging from 0 to an index less than the length of the string.

Examples of charAt() method in Java

Now that we know the theory of the charAt() method, let us put it into implementation as we look at some example programs that make use of this method:

class Main
{
    public static void main(String args[])
    {
        String s = "FirstCode";
        System.out.println(s.charAt(3));
        System.out.println(s.charAt(0));
        System.out.println(s.charAt(8));
        System.out.println(s.charAt(5));
    }
}

Output:

s
F
e
C

Remember we talked about the “Index-Out-OfBound” error that occurs when we specify an index value greater than or equal to the length of the string?

Here is an example that demonstrates this:

class Main
{
    public static void main(String args[])
    {
        String s = "FirstCode";
        System.out.println(s.charAt(9));
    }
}

In the above program, the length of the string “FirstCode” is 9, if we ask charAt() to display the character at the 9th index, it displays the error shown below:

display the character

We can use the charAt() method to implement many applications, let us take a look at a few of them:

1. Counting the Frequency of a Character in a String

class Main 
{
    public static void main(String[] args)
    {
        String str = "Hello! Welcome to FirstCode";
        int count = 0;
        for (int i = 0; i < str.length(); i++) 
        {
            if (str.charAt(i) == 'e') {count++;}
        }
        System.out.println("The character 'e' occurs "+count+" times");
    }
}

Output

The character ‘e’ occurs 4 times

In the above program, we increment the value of “count” each time we come across the occurrence of the character “e” as we traverse the string using the for loop.

2. Printing characters present in odd and even positions

class Main 
{
    public static void main(String[] args)
    {
        String str = "FirstCode";
        System.out.print("Letters in odd Positions: ");
        for (int x = 0; x < str.length(); x += 2) 
        {System.out.print(str.charAt(x));}
        System.out.println("\n");
        System.out.print("Letters in even Positions: ");
        for (int x = 1; x < str.length(); x += 2) 
        {System.out.print(str.charAt(x));}
    }
}

Output:

Letters in Odd Positions: Frtoe
Letters in even Positions: isCd

3. Printing the first and last letters of a string

class Main 
{
    public static void main(String[] args)
    {
        String str = "FirstCode";
        System.out.println("First character: "+ str.charAt(0));
        System.out.println("Last character: " + str.charAt(str.length() - 1));
    }
}

Output:

First character: F
Last character: e

Conclusion

In summary, the charAt() method within the StringBuilder class proves indispensable in Java programming, providing a means to access and manipulate individual characters in strings. Through various examples, we’ve highlighted its versatility, simplicity, and essential role in tasks such as character extraction and modification. As an integral component of string manipulation, the charAt() method significantly enhances the efficiency and functionality of Java applications, making it a valuable tool for developers working with string operations.

Leave a Reply

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