Signup/Sign In
LAST UPDATED: NOVEMBER 24, 2020

Java Character toChars() Method

Java toChars() method is a part of Character class. This method converts the specified Unicode code point character to its UTF-16 representation stored in a char array.

It must be noted that if the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint and if the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.

Syntax:

public static char[] toChars(int codePoint)  

Parameters:

The parameter passed is the Unicode code point value to be converted.

Returns:

Returns a char array having UTF-16 representation of the code point passed as a parameter.

Example 1:

Here, the specified codepoint value is converted to a char array.

public class StudyTonight
{  
	public static void main(String[] args)
	{  
		int cp = 67;  
		char ch[] = Character.toChars(cp);  

		System.out.print("The char array according to UTF-16: " );  

		for (int i = 0; i < ch.length; i++) 
		{  
			System.out.print( ch[i] );  
		}    
	}  
}


The char array according to UTF-16: C

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);	
			System.out.print("The char array according to UTF-16: " );  

			for (int i = 0; i < ch.length; i++) 
			{  
				System.out.print( ch[i] );  
			}  
		}
		catch(Exception e)
		{
			System.out.println("Invalid Input!!");
		}
	}  
}


Enter the codepoint value: 88
The char array according to UTF-16: X
**********************************************
Enter the codepoint value: 101
The char array according to UTF-16: e

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.