Java StringBuffer codePointAt(int index) method returns a code point value of the character present at the specified index. A code point is a numeric value that represents a char, letter, punctuation, space etc. In this guide, we will discuss codePointAt() method with examples.
Syntax of codePointAt() method
//returns code point of first char in the sequence int codePoint = sb.codePointAt(0); //returns code point of last char in the sequence int codePoint = sb.codePointAt(sb.length()-1);
Here, sb is an object of StringBuffer class.
codePointAt() Description
public int codePointAt(int index): Returns code point of character present at the given index.
codePointAt() Parameters
This method takes a single parameter:
- index: An index that gives the position of a character in the char sequence.
codePointAt() Return Value
- Returns an int value that is the code point value of the character.
It throws IndexOutOfBoundsException
, if any of the following condition occurs:
index < 0
index >= sb.length()
Example 1: Unicode code point of first and last char
public class JavaExample { public static void main(String[] args) { StringBuffer sb= new StringBuffer("Hello"); System.out.println("Sequence: " + sb); // code point of first char int cpFirst = sb.codePointAt(0); // code point of last char int cpLast = sb.codePointAt(sb.length()-1); System.out.println("Unicode code Point of first char: "+cpFirst); System.out.println("Unicode code Point of last char: "+cpLast); } }
Output:
Example 2: Code Points of special characters
public class JavaExample { public static void main(String[] args) { StringBuffer sb= new StringBuffer("$ %@"); System.out.println("Sequence: " + sb); // code point for $ int cp1 = sb.codePointAt(0); // code point for whitespace int cp2 = sb.codePointAt(1); // code point for % int cp3 = sb.codePointAt(2); // code point of @ int cp4 = sb.codePointAt(3); System.out.println(cp1+", "+ cp2+", "+ cp3+", "+ cp4); } }
Output:
Example 3: If given index >= length of Sequence
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Welcome"); int cp = sb.codePointAt(7); System.out.println(cp); } }
Output: