Java StringBuilder codePointBefore(int index) method returns the unicode code point for the character before the specified index. For example, sb.codePointBefore(5)
would return the code point for character present at the index 4 in the given sequence sb
.
Syntax of codePointBefore() Method:
int codePoint = sb.codePointBefore(1);
The above statement would return the code point for the first character in the sequence.
codePointBefore() Description
public int codePointBefore(int index): Returns the code point for the character present at index - 1
position.
codePointBefore() Parameters
It takes a single parameter:
- index: Integer index value, it specifies a position in the sequence. The code point for the character just before this position is returned.
codePointBefore() Return Value
- Returns code point value for the character before the given
index
.
It throws IndexOutOfBoundsException
, if any of the following condition occurs:
index < 1
index > sb.length()
Also Read: StringBuilder in Java
Example 1: Code Point value for the first char in the sequence
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Welcome\uD83D\uDE0A"); //code point for first character int codePoint = sb.codePointBefore(1); System.out.println("Code Point value for the first char: "+codePoint); } }
Output:
Example 2: Code Point for surrogate range
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Welcome\uD83D\uDE0A"); //code point for last char int codePoint = sb.codePointBefore(sb.length()); System.out.println("Code Point value for surrogate: "+codePoint); } }
Output:
Example 3: If specified index is 0
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Text"); //if index is 0 int codePoint = sb.codePointBefore(0); System.out.println(codePoint); } }
Output: Exception occurred as it tried to print code point for -1 index which didn’t exist.