Java's String class provides the codePointAt() method for this purpose. It returns the Unicode code point at the specified index. For characters represented by a single UTF-16 code unit, such as most English letters, the returned value corresponds to their Unicode value.
- It returns the Unicode code point at the specified index.
- The index is based on UTF-16 code units, not Unicode characters (code points).
Illustration:
String: G E E K S
Index: 0 1 2 3 4
|
Code: 71 69 69 75 83 , Output: 71Input: str = "Geeks", index = 2
Output: 101

Syntax:
str.codePointAt(index);
- Parameter:
index– the index of the character whose Unicode code point is required. - Return Value: An
intrepresenting the Unicode code point at the specified index.
public class GFG {
public static void main(String[] args) {
String str = "GEEKS";
int result1 = str.codePointAt(0);
int result2 = str.codePointAt(1);
int result3 = str.codePointAt(2);
int result4 = str.codePointAt(3);
int result5 = str.codePointAt(4);
System.out.println("Original String: " + str);
System.out.println("Unicode code point at index 0 = "
+ result1);
System.out.println("Unicode code point at index 1 = "
+ result2);
System.out.println("Unicode code point at index 2 = "
+ result3);
System.out.println("Unicode code point at index 3 = "
+ result4);
System.out.println("Unicode code point at index 4 = "
+ result5);
}
}
Output
Original String: GEEKS Unicode code point at index 0 = 71 Unicode code point at index 1 = 69 Unicode code point at index 2 = 69 Unicode code point at index 3 = 75 Unicode code point at index 4 = 83
Explanation:
- The string "GEEKS" is stored in the str variable.
- codePointAt() is called with different indexes.
- Each call returns the Unicode code point at that index.
- The returned value is stored in an int variable.
- For example, str.codePointAt(0) returns 71, the Unicode code point of 'G'.
Example: Handling an Invalid Index
If the specified index is negative or greater than or equal to the string's length, codePointAt() throws a StringIndexOutOfBoundsException.
public class GFG {
public static void main(String[] args) {
String str = "Geeksforgeeks";
try {
int result1 = str.codePointAt(0);
int result2 = str.codePointAt(-4);
System.out.println("Unicode code point at index 0 = "
+ result1);
System.out.println("Unicode code point at index -4 = "
+ result2);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
Output
Exception: Index -4 out of bounds for length 13
Explanation
- str.codePointAt(0) is valid because 0 is a valid index.
- str.codePointAt(-4) is invalid because string indexes cannot be negative.
- Therefore, StringIndexOutOfBoundsException is thrown.
- The try-catch block handles the exception and prevents abnormal program termination.