The codePointAt() method of the StringBuffer class is used to return the Unicode code point of the character at the specified index. If the character at the specified index is a high surrogate and the next character is a low surrogate, the method returns the Unicode code point represented by the surrogate pair.
- It supports Unicode characters represented using surrogate pairs.
- It throws IndexOutOfBoundsException if the index is invalid.+
public class GFG {
public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer str = new StringBuffer("Geeksforgeeks");
// Get Unicode code point at index 10
int codePoint = str.codePointAt(10);
// Print the result
System.out.println(
"Unicode of Character at Index 10 = " + codePoint);
}
}
Output
Unicode of Character at Index 10 = 101
Explanation: The character at index 10 is e. Its Unicode code point is 101, so codePointAt(10) returns 101.
Syntax
public int codePointAt(int index)
- Parameters:
index–> the index of the character whose Unicode code point is to be returned. - Return Value: Returns the Unicode code point at the specified index.
- Exception: IndexOutOfBoundsException –> thrown if the index is negative or greater than or equal to
length().
Example: To demonstrate IndexOutOfBoundsException
public class GFG {
public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer str =
new StringBuffer("GeeksForGeeks Contribute");
try {
// Index 25 is outside the valid range
int codePoint = str.codePointAt(25);
System.out.println("Code Point: " + codePoint);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception: " + e);
}
}
}
Output
Exception: java.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 24
Explanation: The valid indexes range from 0 to length() - 1. Since index 25 is outside the valid range, codePointAt() throws an IndexOutOfBoundsException.
Advantages of codePointAt()
- Returns the Unicode code point of a character.
- Supports Unicode characters represented by surrogate pairs.
- Useful for working with Unicode text.
- Provides direct access to a character's code point using its index.
- Throws an exception for invalid indexes, helping identify incorrect access.