This article will discuss a couple of ways to convert a character to String in java.

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

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

  1. java.lang.String is internally stored as a character array.
  2. 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”.
  3. 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.
  4. Converting a single character using character array in one-liner form may be written as String str = new String(new char[]{ 'c' });
Do not forget to hit the clap.

Leave a Reply