Signup/Sign In

Java Character toChars(int codePoint, char[] dst, int dstIndex)Method

Java toChars(int codePoint, char[] dst, int dstIndex) method is a part of Character class. This method is used to convert the specified Unicode code point character to its UTF-16 representation.

Syntax:

public static int toChars(int codePoint, char[] dst, int dstIndex)

Parameters:

The parameters passed are:

  • codePoint - the Unicode code point character to be converted.
  • dst - an array of char in which the specified codepoint's UTF-16 value is stored.
  • dstIndex - the start index into the dst array where the converted value is stored.

Returns:

Returns value 1 if the code point is a BMP code point, 2 if the code point is a supplementary code point.

Exceptions:

  • IllegalArgumentException - if the specified codePoint is not a valid Unicode code point.
  • NullPointerException - if the specified dst is null.
  • IndexOutOfBoundsException

Example 1:

Here, the specified code point is converted into the respective UTF-16 representation.

public class StudyTonight
{  
	public static void main(String[] args)
	{  
		int cp1 = 0x0066;  
		int cp2 = 66;  

		char ch1[] = Character.toChars(cp1);  
		char ch2[] = Character.toChars(cp2);  

		int r1 = Character.toChars(cp1, ch1, 0);  
		int r2 = Character.toChars(cp2, ch2, 0);  

		System.out.println("The value is : "+r1);
		System.out.println("The value is : "+r2);
	}  
}


The value is : 1
The value is : 1

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
		{
			System.out.print("Enter the codepoint value: ");  
			Scanner sc = new Scanner(System.in);         
			int cp = sc.nextInt();  
			char ch[] = Character.toChars(cp);	

			int r = Character.toChars(cp, ch, 0);
			System.out.print("The char array according to UTF-16: "+r ); 
		}
		catch(Exception e)
		{
			System.out.println("Invalid Input!!");
		}
	}  
}


Enter the codepoint value: 878
The char array according to UTF-16: 1
***********************************************
Enter the codepoint value: 09
The char array according to UTF-16: 1

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.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.