Character.codePointBefore() in Java

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

Syntax:

int java.lang.Character.codePointBefore(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 preceding the given index of the char array.

Parameters: Two parameters are required for this method.

a: the char array.

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

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

Throws:

1. NullPointerException - if a is null.

2. IndexOutOfBoundsException - if the index argument is less than 1 or greater than the length of the char array.

Approach 1: When no exceptions.

Java

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

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

Output:

108


Approach 2: NullPointerException

Java

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

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


Output:

Exception in thread "main" java.lang.NullPointerException: Cannot load from char array because "a" is null at java.base/java.lang.Character.codePointBeforeImpl(Character.java:9039) at java.base/java.lang.Character.codePointBefore(Character.java:9000)


Approach 3: IndexOutOfBoundsException 

Java

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

        char a[] = { 'h''e''l''l''o' };
        int index = 7;
        System.out.println(Character.codePointBefore(a, index));
    }
}


Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5 at java.base/java.lang.Character.codePointBeforeImpl(Character.java:9039) at java.base/java.lang.Character.codePointBefore(Character.java:9000)


No comments:

Post a Comment