Introduction
In this lab, you will learn how to convert a character char
to a string String
in Java.
In this lab, you will learn how to convert a character char
to a string String
in Java.
valueOf()
MethodOpen your terminal and create a Java file using the below command:
touch ConvertCharToString.java
Open 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.java
Run the Java code using the below command in the terminal:
java ConvertCharToString
The output will be:
s
s
java.lang.String
toString()
MethodOpen the same ConvertCharToString.java
file 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.java
Run the Java code using the below command in the terminal:
java ConvertCharToString
The output will be:
s
s
java.lang.String
+
OperatorOpen the same ConvertCharToString.java
file 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.java
Run the Java code using the below command in the terminal:
java ConvertCharToString
The output will be:
s
s
java.lang.String
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.