Character.codePointCount() char array in Java

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

Syntax:

int java.lang.Character.codePointCount(char[] a, int offset, int count)

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 number of Unicode code points in a subarray of the char array argument. The offset argument is the index of the first char of the subarray and the count argument specifies the length of the subarray in chars.

Parameters: Three parameters are required for this method.

a: The char array.

offset: The index of the first char in the given char array.

count: The length of the subarray in chars.

Returns: the number of Unicode code points in the specified subarray.

Throws:

1. NullPointerException - if a is null.

2. IndexOutOfBoundsException - if offset or count is negative, or if offset +count is larger than the length of the given array.

Approach 1: When no exceptions.

Java

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

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

Output:

3


Approach 2: NullPointerException 

Java

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

        char a[] = null;
        int offset = 0, count = 3;
        System.out.println(Character.codePointCount(a, offset, count));
    }
}


Output:

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



Approach 3: IndexOutOfBoundsException 

Java

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

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


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.lang.Character.codePointCount(Character.java:9245)


No comments:

Post a Comment