This example shows how to convert char to String in Java. It also shows how to convert a character to String using several methods and the best way among them.
How to convert char to String in Java?
1) Conver char to String using the valueOf method of the String class
You can use the valueOf
static method of the String class to convert.
1 |
static String valueOf(char c) |
The valueOf
method returns a string representation of the specified character argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javacodeexamples.basic; public class CharToStringExample { public static void main(String[] args){ char c = 'a'; String strChar = String.valueOf(c); System.out.println("String value: " + strChar); } } |
Output
1 |
String value: a |
2) Using the Character wrapper class
Use the toString
method of the Character
wrapper class to convert.
1 |
public static String toString(char c) |
This method returns a string representation of the character value passed as a parameter.
1 2 3 4 |
char c = 'a'; String strChar = Character.toString(c); System.out.println("String value: " + strChar); |
Output
1 |
String value: a |
3) Using the string concatenation
String concatenation can be indirectly used to convert Java primitive values to a string as given below.
1 2 3 4 |
char c = 'a'; String strChar = "" + c; System.out.println("String value: " + strChar); |
Output
1 |
String value: a |
What is the best way to convert?
The valueOf
method of the String class internally calls the toString
method of the Character
wrapper class to convert from char to a string value. Using either of the methods is equally efficient in terms of performance. The preferred way is to use the toString
method of the Character
wrapper class.
String concatenation should be avoided mainly for the conversion purpose because,
a) It is difficult to visually understand that the purpose of the code statement is conversion.
b) String concatenation operation creates unnecessary temporary objects during the conversion process. String concatenation is achieved using the append method of the StringBuffer or StringBuilder class. So the code,
1 |
String strChar = "" + c; |
Will be executed like,
1 2 3 4 5 6 |
StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(c); String strNumber = sb.toString(); |
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.