Java StringBuffer charAt() Examples

Java StringBuffer charAt() method returns the char value at the specified index. An index ranges from zero to length() - 1. The first char value of the sequence is at index zero, the next at index one, and so on, as for array indexing.

To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method.
Java StringBuffer charAt() method throws IndexOutOfBoundsException - if an index is negative or greater than or equal to length().

Java StringBuffer charAt() Examples

Example 1: Returns the char value at the specified index of this string. The first char value is at index 0.
StringBuffer buffer = new StringBuffer("Welcome to string handling guide");
char ch1 = buffer.charAt(0);
char ch2 = buffer.charAt(5);
char ch3 = buffer.charAt(11);
char ch4 = buffer.charAt(20);
System.out.println("Character at 0 index is: " + ch1);
System.out.println("Character at 5th index is: " + ch2);
System.out.println("Character at 11th index is: " + ch3);
System.out.println("Character at 20th index is: " + ch4);
Output:
Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n
Example 2: Example to throws IndexOutOfBoundsException - if index is negative or greater than or equal to length().
public static void charAtExample2() {
StringBuffer builder = new StringBuffer("Java Guides");
char ch1 = builder.charAt(builder.length());
System.out.println("character :: " + ch1);
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
 at java.lang.StringBuffer.charAt(StringBuffer.java:202)
 at com.javaguides.stringbuffer.methods.ChatAtExample.charAtExample2(ChatAtExample.java:26)
 at com.javaguides.stringbuffer.methods.ChatAtExample.main(ChatAtExample.java:6)
Example 3: Example how to get a first and last character of the string
public static void charAtExample3() {
StringBuffer buffer = new StringBuffer("Java Guides");
int strLength = buffer.length() - 1;
// Fetching first character
System.out.println("Character at 0 index is: " + buffer.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + buffer.charAt(strLength));
Output:
Character at 0 index is: J
Character at last index is: s

Reference

Comments