How to Convert char to String in Java
How to Convert char to String in Java
There are two methods to convert char to String:
- Using String.valueOf(char) method
- Using Charcter.toString(char) method
Using String.valueOf(char) method
valueOf(char) is the static method of String class that belongs to java.lang package. It returns the new String object. It is the most efficient method to convert char to String. The signature of the method is given below:
public static String valueOf(char c)
Example
In this example, ch is a variable that contains a character ‘U’. str is a variable of type String that stores the string returned by valueOf() method. The println statement prints the converted string.
public class CharToStringExample { public static void main(String args[]) { char ch='U'; String str=String.valueOf(ch); System.out.println("String is: "+str); } }
Output
String is: U
Using Character.toString(char) method
toString(char) is the method of Character class. It returns the String class object representing the specified character value. The signature of the method is given below:
public static Character valueOf(char ch)
Example
In this example, ch is a variable of character type initialized with the character ‘T.’ str is a variable of type String. Character is a wrapper class. toString() is a method that parses ch as an argument and returns the String class object representing the specifies character value ch. The println statement prints the converted string.
public class ChartoStringExample1 { public static void main(String[] args) { char ch = 'T'; String Str = Character.toString(ch); System.out.println("String is: "+Str); } }
Output
String is: T