Introduction
In this lab, you will learn how to convert a character char to a string String in Java.
Convert Char to String Using valueOf() Method
Open your terminal and create a Java file using the below command:
touch ConvertCharToString.javaOpen the file using a text editor and paste the below code:
public class ConvertCharToString { public static void main(String[] args) { char ch = 's'; System.out.println(ch); String str = String.valueOf(ch); System.out.println(str); System.out.println(str.getClass().getName()); } }Compile the Java code using the below command in the terminal:
javac ConvertCharToString.javaRun the Java code using the below command in the terminal:
java ConvertCharToStringThe output will be:
s s java.lang.String
Convert Char to String Using toString() Method
Open the same
ConvertCharToString.javafile in the text editor and replace the main method with the below code:public static void main(String[] args){ char ch = 's'; System.out.println(ch); String str = Character.toString(ch); System.out.println(str); System.out.println(str.getClass().getName()); }Compile the Java code using the below command in the terminal:
javac ConvertCharToString.javaRun the Java code using the below command in the terminal:
java ConvertCharToStringThe output will be:
s s java.lang.String
Convert Char to String Using + Operator
Open the same
ConvertCharToString.javafile in the text editor and replace the main method with the below code:public static void main(String[] args){ char ch = 's'; System.out.println(ch); String str = ""+ch; System.out.println(str); System.out.println(str.getClass().getName()); }Compile the Java code using the below command in the terminal:
javac ConvertCharToString.javaRun the Java code using the below command in the terminal:
java ConvertCharToStringThe output will be:
s s java.lang.String
Summary
In this lab, you have learned how to convert a character char to a string String in Java using different methods. You can use either valueOf() or toString() methods or plus (+) operator to convert a character to a string.



