StringBuffer codePointAt() in Java

codePointAt(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

int java.lang.StringBuffer.codePointAt(int index)

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

Parameters: One parameter is required for this method.

index: the index to the char values.

Returns: the code point value of the character at the index.

Throws:

IndexOutOfBoundsException - if the index argument is negative or not less than the length of this sequence.

For Example:

StringBuffer str = new StringBuffer("Hello World!")

int index = 2

str.codePointAt(index) = > It returns 108.

Approach 1: When index is in the range.

Java

public class CodePointAt {
    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("Hello World!");

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

Output:

108


Approach 2: When the index is out of range.

Java

public class CodePointAt {
    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("Hello World!");

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


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 15, length 12 at java.base/java.lang.String.checkIndex(String.java:3693) at java.base/java.lang.AbstractStringBuilder.codePointAt(AbstractStringBuilder.java:382) at java.base/java.lang.StringBuffer.codePointAt(StringBuffer.java:246)


No comments:

Post a Comment