Character.codePointAt() CharSequence in Java

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

Syntax:

int java.lang.Character.codePointAt(CharSequence seq, int index)

This method takes two arguments, one of type CharSequence and another of type int as its parameters. This method returns the code point at the given index of the CharSequence.

Parameters: Two parameters are required for this method.

seq: a sequence of char values (Unicode code units).

index: the index to the char values (Unicode code units) in seq to be converted.

Returns: the Unicode code point at the given index.

Throws:

1. NullPointerException - if seq is null.

2. IndexOutOfBoundsException - if the value index is negative or not less than seq.length().

Approach 1: When no exceptions.

Java

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

        CharSequence seq = "Hello";

        int index = 3;
        System.out.println(Character.codePointAt(seq, index));
    }
}

Output:

108


Approach 2: NullPointerException

Java

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

        CharSequence seq = null;

        int index = 3;
        System.out.println(Character.codePointAt(seq, index));
    }
}


Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.charAt(int)" because "seq" is null at java.base/java.lang.Character.codePointAt(Character.java:8867)


Approach 3: IndexOutOfBoundsException

Java

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

        CharSequence seq = "Hello";

        int index = 7;
        System.out.println(Character.codePointAt(seq, index));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:712) at java.base/java.lang.Character.codePointAt(Character.java:8867)


No comments:

Post a Comment