Character.codePointAt() in Java

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

Syntax:

int java.lang.Character.codePointAt(char[] a, int index)

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

Parameters: Two parameters are required for this method.

a: the char array.

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

Returns: the Unicode code point at the given index.

Throws:

1. NullPointerException - if a is null.

2. IndexOutOfBoundsException - if the value index is negative or not less than the length of the char array.

Approach 1: When no exceptions.

Java

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

        char a[] = { 'h''e''l''l''o' };
        int index = 3;

        System.out.println(Character.codePointAt(a, index));
    }
}

Output:

108


Approach 2: NullPointerException.

Java

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

        char a[] = null;
        int index = 3;

        System.out.println(Character.codePointAt(a, index));
    }
}


Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "a" is null at java.base/java.lang.Character.codePointAt(Character.java:8899)


Approach 3: IndexOutOfBoundsException 

Java

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

        char a[] = { 'h''e''l''l''o' };
        int index = 7;

        System.out.println(Character.codePointAt(a, index));
    }
}


Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 at java.base/java.lang.Character.codePointAtImpl(Character.java:8936) at java.base/java.lang.Character.codePointAt(Character.java:8899)


No comments:

Post a Comment