Java StringBuffer charAt() Method
Last Updated : 09 Dec, 2024
Improve
The charAt() method in the StringBuffer class in Java is used to retrieve the character at a given index in a StringBuffer object. This method allows us to access individual characters in a StringBuffer by specifying the index.
Example 1: Here, we will use a valid index to retrieve a character from the StringBuffer object.
// Java program to demonstrate charAt() method
public class CharAt {
public static void main(String[] args) {
StringBuffer b = new StringBuffer("Java Programming");
// Using charAt() to get the
// character at index 5
char ch = b.charAt(5);
System.out.println("" + ch);
}
}
Output
P
Syntax of charAt()
Method
public char charAt(int index)
- Parameters:
index
: This is an integer representing the index of the character to be fetched. - Return Type:
char
: The character at the specified index.
Example 2: If we use charAt() with a Negative Index a StringIndexOutOfBoundsException is thrown, as negative indices are not allowed.
// Java program to demonstrate
// invalid negative index in charAt()
public class CharAt {
public static void main(String[] args) {
StringBuffer b = new StringBuffer("Java Programming");
try {
// Using a negative index
System.out.println("Character at index -1: "
+ b.charAt(-1));
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception: " + e);
}
}
}
Output
Exception: java.lang.StringIndexOutOfBoundsException: index -1,length 16
Example 3: If we pass an index greater than or equal to the length of the StringBuffer object will also result in a StringIndexOutOfBoundsException.
// Java program to demonstrate invalid index
// greater than length in charAt()
public class CharAt {
public static void main(String[] args) {
StringBuffer b = new StringBuffer("Java Programming");
try {
// Using an index greater than the length of the buffer
System.out.println("Character at index 20: "
+ b.charAt(20));
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception: " + e);
}
}
}
Output
Exception: java.lang.StringIndexOutOfBoundsException: index 20,length 16