Java Character toString() Example


Java is a simple language to practice and develop more code in less time. All this is due to predefined API methods designers add in each version. Good examples are classes like String, Character, GregorianCalendar and LinkedList etc. They are designed as classes and methods are given to manipulate them. For example, addFirst() and addLast() methods add new links at the head and tail part of linked list without bothering link and address manipulations. The present context is Character class. Many methods are given to manipulate a character value. One such method is toString() method, overloaded two times.

Following are the method signatures:

  • public String toString(): Returns the Character object (representing a char) as a string. This method overrides the toString() method of Object class. This method is to be used to convert a Character object into string form.
  • public static String toString(char ch): Returns a string representing the char ch. This method is to be used to convert a char into string form. Introduced with JDK 1.4
Following Java Character toString() Example and notes illustrate 3 styles of converting a char to a string form.
public class CharacterFunctionDemo
{
  public static void main(String args[])
  {
    Character c1 = new Character('A');                   // 1st style using toString() method
    String str1 = c1.toString();
    System.out.println("Character object representing char A in string form: " + str1); 

    char ch = 'A';
    String str2 = Character.toString(ch);
    System.out.println("char A in string form: " + str2); 

    System.out.println("\nAnother way to convert using String class valueOf():");
    String str3 = String.valueOf(ch);                   // 2nd style using valueOf() method
    System.out.println("char A in string form: " + str3);     
  }
}

Java Character toString() Example

Still simpler way is to concat char to an empty string. That is all.

char ch = 'A';
String str = "" + ch;                               // 3rd style concatenating with empty string
System.out.println(str);     

Leave a Comment

Your email address will not be published.