Character.offsetByCodePoints(): This method is available in java.lang.Character class of Java.
Syntax:
int java.lang.Character.offsetByCodePoints(CharSequence seq, int index, int codePointOffset)
This method takes three arguments, one of type CharSequnce and the other two are of type int as its parameter. This method returns the index within the given char sequence that is offset from the given index by codePointOffsetcode points.
Parameters: Three parameters are required for this method.
seq: the char sequence.
index: the index to be offset.
codePointOffset: the offset in code points.
Returns: the index within the char sequence.
Throws:
1. NullPointerException - if seq is null.
2. IndexOutOfBoundsException - if the index is negative or larger then the Length of the char sequence, or if codePointOffset is positive and the subsequence starting with index has fewer than codePointOffset code points, or if codePointOffset is negative and the subsequence before index has fewer than the absolute value of codePointOffset code points.
Approach 1: When no exceptions.
Java
public class CharacteroffsetByCodePointsCharSequence {public static void main(String[] args) {CharSequence seq = null;int index = 2, codePointOffset = 3;System.out.println(Character.offsetByCodePoints(seq,index, codePointOffset));}}
Output:
5
Approach 2: NullPointerException
Java
public class CharacteroffsetByCodePointsCharSequence {public static void main(String[] args) {CharSequence seq = null;int index = 2, codePointOffset = 3;System.out.println(Character.offsetByCodePoints(seq,index, codePointOffset));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.length()" because "seq" is null at java.base/java.lang.Character.offsetByCodePoints(Character.java:9287)
Approach 3: IndexOutOfBoundsException
Java
public class CharacteroffsetByCodePointsCharSequence {public static void main(String[] args) {CharSequence seq = "Hello Java";int index = -1, codePointOffset = 3;System.out.println(Character.offsetByCodePoints(seq,index, codePointOffset));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.lang.Character.offsetByCodePoints(Character.java:9289)
No comments:
Post a Comment