Java StringBuilder 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);
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: Integer parameter. It represents the char in the 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: Code Point of first and last character
public class JavaExample { public static void main(String[] args) { StringBuilder sb= new StringBuilder("BeginnersBook"); 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("Code Point of first char: "+cpFirst); System.out.println("Code Point of last char: "+cpLast); } }
Output:
Example 2: Code Point of Special Characters
public class JavaExample { public static void main(String[] args) { StringBuilder sb= new StringBuilder(" $%@"); System.out.println("Sequence: " + sb); // code point for whitespace int cp1 = sb.codePointAt(0); // code point for $ 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 index >= length of sequence
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Text"); int cp = sb.codePointAt(4); System.out.println(cp); } }
Output: