This article will discuss a couple of ways to convert a character to String in java.
[the_ad id=”644″]
Method 1 : Using java.lang.Character Wrapper class
java.util.Characteris 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
[the_ad id=”647″]
Method 2 : Using Character array
java.lang.Stringclass 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.Stringis 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.Stringconstructor 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' });
Leave a Comment