Character.codePointBefore() char array in Java

Character.codePointBefore(): This methos is available in java.lang.Character class of Java.

Syntax:

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

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 preceding the given index of the char array, where only array elements with an index greater than or equal to start can be used.

Parameters: Three parameters are required for this method.

a: the char array.

index: the index following the code point that should be returned.

start: the index of the first array element in the char array.

Returns: the Unicode code point value before the given index.

Throws:

1. NullPointerException - if a is null.

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

Approach 1: When no exceptions.

Java

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

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

        int index = 3;
        int start = 0;
        System.out.println(Character.codePointBefore(a, index, start));
    }
}

Output:

108


Approach 2: NullPointerException 

Java

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

        char a[] = null;

        int index = 3;
        int start = 0;
        System.out.println(Character.codePointBefore(a, index, start));
    }
}


Output:

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


Approach 3: IndexOutOfBoundsException

Java

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

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

        int index = -1;
        int start = 0;
        System.out.println(Character.codePointBefore(a, index, start));
    }
}


Output:

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


No comments:

Post a Comment