Signup/Sign In

Java Character toString() Method

Java toString() method is a part of the Character class of the java.lang package. This method returns the String object representing this Character value. The result is a string of length 1 whose sole component is the primitive char value represented by this Character object. This method overrides the toString() method of the Object class.

In short, this method is used to convert Character Object into String.

Syntax:

public String toString()  

Parameters:

No parameters are passed in this method.

Returns:

Returns the String representation of the Character Object.

Example 1:

Here, the Character objects are converted into its equivalent String representations.

public class StudyTonight
{  
	public static void main(String[] args) 
	{  
		Character ch1 = 'D';       
		String s1 = ch1.toString();  // return a string value 
		System.out.println("The string value is " + s1);              

		Character ch2 = 'u';                    
		String s2 = ch2.toString();  // return a string value 
		System.out.println("The String value is " + s2);  
	}  
} 


The string value is D
The String value is u

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 value ");  
			Scanner sc = new Scanner(System.in);  
			Character ch = sc.next().charAt(0);  
			String s = ch.toString(); //converting to string
			System.out.println("String value is : "+ s);          
		}
		catch(Exception e)
		{
			System.out.println("Invalid input!!");
		}
	}  
}  


Enter the value U
String value is : U
************************
Enter the value w
String value is : w

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.