StringBuilder codePointBefore() in Java

codePointBefore(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

int java.lang.AbstractStringBuilder.codePointBefore(int index)

This method takes one argument of type int as its parameter. This method returns the character (Unicode code point) before the specified index. The index refers to char values(Unicode code units) and ranges from 1 to length().

Parameters: One parameter is required for this method.

index: the index following the code point that should be returned.

Returns: the Unicode code point value before the given index.

Throws:

StringIndexOutOfBoundsException - if the index argument is less than 1 or greater than the length of this sequence.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int index = 2

str.codePointBefore(index) = > It returns 101.

Approach 1: When the index is in the range.

Java

public class CodePointBefore {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = 2;
        System.out.println(str.codePointBefore(index));
    }
}

Output:

101


Approach 2: When the index is in the range.

Java

public class CodePointBefore {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = 15;
        System.out.println(str.codePointBefore(index));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 15 at java.base/java.lang.AbstractStringBuilder.codePointBefore(AbstractStringBuilder.java:413) at java.base/java.lang.StringBuilder.codePointBefore(StringBuilder.java:85)


No comments:

Post a Comment