How to Convert a Char to a String in Java
Hassan Saeed
Feb 02, 2024
-
String.valueOf()
to Convert Char to String in Java -
Character.toString()
to Convert Char to String in Java -
String
Concatenation to Convert Char to String in Java
This tutorial discusses three methods to convert a char to a string in Java.
String.valueOf()
to Convert Char to String in Java
The most efficient way is to use the built-in function of the String
class - String.valueOf(ch)
.
The below example illustrates this:
public class MyClass {
public static void main(String args[]) {
char myChar = 'c';
String charToString = String.valueOf(myChar);
System.out.println(charToString);
}
}
Output:
c
Character.toString()
to Convert Char to String in Java
We can also use the built-in method of Character
class to convert a character to a String
.
The below example illustrates this:
public class MyClass {
public static void main(String args[]) {
char myChar = 'c';
String charToString = Character.toString(myChar);
System.out.println(charToString);
}
}
Output:
c
String
Concatenation to Convert Char to String in Java
This method simply concatenates the given character with an empty string to convert it to a String.
The below example illustrates this.
public class MyClass {
public static void main(String args[]) {
char myChar = 'c';
String charToString = myChar + "";
System.out.println(charToString);
}
}
Output:
c
However, this is the least efficient method of all since the seemingly simple concatenation operation expands to new StringBuilder().append(x).append("").toString();
which is more time consuming than the other methods we discussed.
Related Article - Java String
- How to Perform String to String Array Conversion in Java
- How to Remove Substring From String in Java
- How to Convert Byte Array in Hex String in Java
- How to Convert Java String Into Byte
- How to Generate Random String in Java
- The Swap Method in Java