Java StringBuilder.charAt() – Examples

In this tutorial, we will learn about the Java StringBuilder.charAt() function, and learn how to use this function to get char value at specified index in the StringBuilder, with the help of examples.

charAt(int index)

StringBuilder.charAt() returns the char value in this sequence (StringBuilder object) at the specified index.

ADVERTISEMENT

Syntax

The syntax of charAt() function is

charAt(int index)

where

ParameterDescription
indexAn integer representing the index of desired char value in StringBuilder sequence.

Returns

The function returns char at the specified index.

Example 1 – charAt(int index)

In this example, we will create a StringBuilder object with some initial string literal. We will take index variable with value of 3. We will find the char in StringBuilder at this index, using charAt() method.

Java Program

public class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object 
        StringBuilder stringBuilder = new StringBuilder("abcdefgh"); 
        // get char at index
        int index = 3;
        char ch = stringBuilder.charAt(index); 
        // print the result 
        System.out.println("StringBuilder sequence  : " + stringBuilder.toString()); 
        System.out.println("Character at index " + index + " is : " + ch);   
    } 
}

Output

StringBuilder sequence  : abcdefgh
Character at index 3 is : d

Example 2 – charAt(int index)

In this example, we will create a StringBuilder object with some initial string literal. We will take index variable with value of 13, where 13 is out of range of the sequence in the StringBuilder. Under such scenario, charAt() method throws java.lang.StringIndexOutOfBoundsException.

Java Program

public class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object 
        StringBuilder stringBuilder = new StringBuilder("abcdefgh"); 
        // get char at index
        int index = 13;
        char ch = stringBuilder.charAt(index); 
        // print the result 
        System.out.println("StringBuilder sequence  : " + stringBuilder.toString()); 
        System.out.println("Character at index " + index + " is : " + ch);   
    } 
}

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 13,length 8
	at java.base/java.lang.String.checkIndex(Unknown Source)
	at java.base/java.lang.AbstractStringBuilder.charAt(Unknown Source)
	at java.base/java.lang.StringBuilder.charAt(Unknown Source)
	at Example.main(Example.java:7)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java StringBuilder.charAt() function, and also learnt how to use this function with the help of examples.