Java :: How to Convert Primitive Char to String in Java
Char is 16 bit unsigned data type in Java used to store characters and String is an immutable array of char. In Java you cannot cast a primitive char element to String.
Below I have given five methods to convert a char to String. Also I have included common mistakes that gives compile time errors.
packagecom.deepumohan.tech.chartostring;publicclassCharToString{publicstaticvoidmain(String[]args){charx='x';System.out.println(concatBlankString(x));System.out.println(stringValueOf(x));System.out.println(characterToString(x));System.out.println(characterObjectToString(x));System.out.println(charArray(x));}// append a blank stringpublicstaticStringconcatBlankString(charx){returnx+"";}// use String.valueOf(char) static functionpublicstaticStringstringValueOf(charx){returnString.valueOf(x);}// use Character.toString(char) static functionpublicstaticStringcharacterToString(charx){returnCharacter.toString(x);}// create new Character object from the given char and// then use object's toString() methodpublicstaticStringcharacterObjectToString(charx){returnnewCharacter(x).toString();}// create new char[] array from the char and pass it to// String constructorpublicstaticStringcharArray(charx){returnnewString(newchar[]{x});}/* // Compile time error // No suitable constructor found public static String noConstructor(char x) { return new String(x); } // Compile time error // Inconvertible types public static String inconvertibleTypes(char x) { return (String) x; } */}
I wonder why Java doesn’t include String constructor that accept a single char as argument.