Trusted answers to developer questions

What is StringBuilder.charAt in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

The charAt method can be used to get the character at the specific index of the string of the StringBuilder.

Syntax

public char charAt(int index);

Such a method returns the character at the passed index.

The index value should be positive and less than the length of the string. Otherwise, IndexOutOfBoundsException will be thrown.

The value of the index argument acts like an array indexing. For example, index 0 denotes the first character.

Code

class CharAtExample {
public static void main( String args[] ) {
StringBuilder str = new StringBuilder();
str.append("Educative");
for(int i = 0; i < str.length();i++){
char ch = str.charAt(i);
System.out.println("The character at index " + i + " is : " + ch);
}
}
}

In the code above, we created a StringBuilder and appended the string "Educative" to it. We then looped the StringBuilder from index 0 and printed the character at each index inside the loop.


Point to be noted

If the character at a specific index is a surrogate, then the surrogate value is returned.

For example:

class CharAtExample {
public static void main( String args[] ) {
StringBuilder str = new StringBuilder();
str.append("😃"); //😃 is equal to 2 characters -- \uD83D\uDE02
System.out.println("The character at index 0 is : " + str.charAt(0) +", char code is : " + str.codePointAt(0));
System.out.println("The character at index 1 is : " + str.charAt(0) +", char code is : " + str.codePointAt(1));
}
}

Explanation

In the code above, we did the following:

  • We created a StringBuilder and appended the 😃 emoji to it.

  • Internally, the 😃 is formed by combining two characters \uD83D\uDE02 because the char type in Java is 16-bit, we cannot represent all Unicode characters(like emoji) within the 16-bit.

  • The charAt method will return the surrogate value of the \uD83D\uDE02 when we ask for charAt(0). We also printed the code point of the specific character.

Read more about handling emoji here.

RELATED TAGS

charat
stringbuilder
java
Did you find this helpful?