This article will discuss a couple of ways to convert a character to String in java.
java.util.Character
is a wrapper class of primitive char
. It has a static method toString()
which takes a character and returns the String equivalent of the character as shown below :
public class CharacterToStringConverter { static void charToString(){ char c = 'A'; String str = Character.toString(c); boolean isString = str instanceof String; System.out.println(isString); } public static void main(String... a) { charToString(); } }
Output :
true
Method 2 : Using Character array
java.lang.String
class has a constructor which takes a character array and returns a String.
For converting a character to a String, we can create a character array, add the character to this array and pass it to the String constructor to get its String equivalent.
public class CharacterToStringConverter { static void charToString(){ char[] array = new char[1]; array[0] = 'c'; String str = new String(array); boolean isString = str instanceof String; System.out.println(isString); } public static void main(String... a) { charToString(); } }
Output :
true
Let’s tweak in
java.lang.String
is internally stored as a character array.- If the character array contains multiple characters, then the resultant String is a combination of those characters.
For Example, if the character array contains ‘c’, ‘o’, ‘D’, ‘i’, ‘p’, ‘p’, ‘a’, then the String created would be “coDippa”. java.lang.String
constructor which takes a character array as argument, creates a copy of this character array and stores it in the character array which actually holds String value.- Converting a single character using character array in one-liner form may be written as
String str = new String(new char[]{ 'c' });