Character.codePointAt() char array limit 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, int limit)

This method takes three arguments, one of type char array and the other two are of type int as its parameters. This method returns the code point at the given index of the char array, where only the array elements with an index less than the limit can be used.

Parameters: Three 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.

limit: the index after the last array element that can be used in the char array.

Returns: the Unicode code point at the given index.

Throws:

1. NullPointerException - if a is null.

2. IndexOutOfBoundsException - if the index argument is negative or not less than the limit argument, or if the limit argument is negative or greater than the length of the char array.

Approach 1: When no Exceptions.

Java

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

        char a[] = { 'h''e''l''l''o' };
        int index = 0;
        int limit = 3;
        System.out.println(Character.codePointAt(a, index, limit));
    }
}

Output:

104


Approach 2: NullPointerException

Java

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

        char a[] = null;
        int index = 0;
        int limit = 3;
        System.out.println(Character.codePointAt(a, index, limit));
    }
}


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:8928)


Approach 3: IndexOutOfBoundsException

Java

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

        char a[] = { 'h''e''l''l''o' };
        int index = -1;
        int limit = 3;
        System.out.println(Character.codePointAt(a, index, limit));
    }
}


Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 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:8931)


No comments:

Post a Comment