Character.codePointBefore() CharSequence in Java

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

Syntax:

int java.lang.Character.codePointBefore(CharSequence seq, int index)

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

Parameters: Two parameters are required for this method.

seq: the CharSequence instance.

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 seq is null.

2. IndexOutOfBoundsException - if the index argument is less than 1 or greater than seq.length().

Approach 1: When no exceptions.

Java

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

        CharSequence seq = "Hello";
        int index = 3;
        System.out.println(Character.codePointBefore(seq, index));
    }
}

Output:

108


Approach 2: NullPointerException 

Java

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

        CharSequence seq = null;
        int index = 3;
        System.out.println(Character.codePointBefore(seq, index));
    }
}


Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.charAt(int)" because "seq" is null at java.base/java.lang.Character.codePointBefore(Character.java:8968)


Approach 3: IndexOutOfBoundsException 

Java

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

        CharSequence seq = "Hello";
        int index = 7;
        System.out.println(Character.codePointBefore(seq, index));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:712) at java.base/java.lang.Character.codePointBefore(Character.java:8968)


No comments:

Post a Comment