方法一:使用Character.toString()
Character类提供了一个静态方法toString()用来将字符转换成字符串。
char ch = 'U';
String charToString = Character.toString(ch);
方法二:使用字符串连接符
当我们使用字符串连接符的时候,会自动将其他类型的变量转换为字符串类型,如下:
char ch = 'U';
String str = "" + ch;
方法三:使用匿名数组(anonymous array)
java中的匿名数组可以被用来封装一个单独的字符到字符数组,然后将这个字符数组作为String的构造器参数。
char ch = 'U';
String fromChar = new String(new char[]{ch});
方法四:使用String.valueOf()
char ch = 'U';
String valueOfchar = String.valueOf(ch);
下面是完整的示例代码:
public class CharToStringExample {
public static void main(String args[]) {
char ch = 'U';
// char to string using Character class
String charToString = Character.toString(ch);
System.out.println("Converting Char to String using Character class: " + charToString);
// char to String using String concatenation
String str = "" + ch;
System.out.println("Converting Char to String using String concatenation: " + str);
// char to String using anonymous array
String fromChar = new String(new char[] { ch });
System.out.println("Converting Char to String using anonymous array: " + fromChar);
// char to String using String valueOf
String valueOfchar = String.valueOf(ch);
System.out.println("Converting Char to String using String valueOf: " + valueOfchar);
}
}
Output:
Converting Char to String using Character class: U
Converting Char to String using String concatenation: U
Converting Char to String using anonymous array: U
Converting Char to String using String valueOf: U