New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs

Java Character offsetByCodePoints(CharSequence seq, int index, int codePointOffset) Method

Java offsetByCodePoint(CharSequence seq, int index, int codePointOffset) method is a part of Character class. This method returns the index within the given char sequence that is offset from the given index by codePointOffset code points. Unpaired surrogates within the text range given by index and codePointOffset count as one code point each.

Syntax:

public static int offsetByCodePoints(CharSequence seq, int index, int codePointOffset)

Parameters:

The parameters passed are:

  • seq - the char sequence
  • index - the index to be offset
  • codePointOffset - the offset in code points

Returns:

Returns the index within the char sequence.

Exceptions:

  • NullPointerException - if seq is null.
  • IndexOutOfBoundsException - if index is negative or larger then the length of the char sequence.

Example 1:

Here the index within the specified char sequence is returned.

public class StudyTonight
{  
	public static void main(String[] args)
	{  
		CharSequence cs = "Java is easy"; 

		int index = 0;  
		int codePointOffset = cs.length();  

		int r = Character.offsetByCodePoints(cs,index,codePointOffset);  
		System.out.println("The index within the specified range is : " + r);  
	}
}


The index within the specified range is : 12

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner; 
public class StudyTonight
{  
	public static void main(String[] args)
	{  
		try
		{
			Scanner sc = new Scanner(System.in); 
			System.out.print("Enter the char sequence ");
			CharSequence cs = sc.next();
			System.out.print("Enter index and codePointOffset");

			int index = sc.nextInt();
			int offset = sc.nextInt();

			int r = Character.offsetByCodePoints(cs,index, offset);  
			System.out.println("The index within the specified range is : " + r);
		}
		catch(Exception e)
		{
			System.out.println("Invalid Input!!");
		}
	}
}


Enter the char sequence studytonight
Enter index and codePointOffset 2 4
The index within the specified range is : 6
****************************************************
Enter the char sequence infinite
Enter index and codePointOffset 0 9
Invalid Input!!

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.