Java StringBuffer codePointBefore(int index) method returns the unicode code point value 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
. Here, sb
is an object of StringBuffer
class.
Syntax of codePointBefore() method
int codePoint = sb.codePointBefore(1);
This statement will return the code point value 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()
Example 1: Code Point value for the first char
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello\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 character
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello\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 the desired char is out of range
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); //if index is 0 int codePoint = sb.codePointBefore(0); System.out.println(codePoint); } }
Output: