Convert char to string in Java


JavaViews 1891

In this tutorial, we will discuss various methods on how to convert char to String in Java. As we know, a char data type stores a single character whereas a String stores an array of characters.

Convert char to String in Java

Char to String conversion methods in Java

How to convert char to String in Java

Convert char to String in Java using String.valueOf

One of the most efficient methods to convert a char to string in Java is to use the valueOf() method in the String class. This method accepts the character as a parameter and converts it into a String. Let us see an example below.

public class CharToString {

  public static void main(String[] args) {
    char c = 'a';
    String s = String.valueOf(c);
    System.out.println("String equivaluent of character '" + c + "' is " + s );

  }

}
String equivaluent of character 'a' is a

Using Character.toString

Another method is to use the toString() method of the Character wrapper class. Internally, it behaves in the same way as valueOf() method. This is also an efficient way to convert a char to string in Java. Below is a simple example.

public class CharToString {

  public static void main(String[] args) {
    char ch = 'j';
    String s = Character.toString(ch);

    System.out.println("String equivaluent of character '" + ch + "' is " + s );
    
  }

}
String equivaluent of character 'j' is j

Convert using Character constructor

Another way is to use a Character constructor along with the toString() method. However, this is not recommended since we are unnecessarily creating a Character constructor. This method is deprecated from Java 9.

public class CharToString {

  public static void main(String[] args) {
    char d = 'r';
    String s = new Character(d).toString();

    System.out.println("String equivaluent of character '" + d + "' is " + s );
    
  }

}
String equivaluent of character 'r' is r

Using String concatenation

We can convert a char to a string by concatenating it with an empty string. This method is not recommended due to its worst performance. For string concatenation, we can use the “+” symbol.

public class CharToString {

  public static void main(String[] args) {
    char a = 't';
    String s = a + "";
    System.out.println("String equivaluent of character '" + a + "' is " + s );
    
  }

}
String equivaluent of character 't' is t

Using String.format

We can also use the format() method of the String class. For this, we pass the parameter as “%c” which denotes that we want to convert a char to String format.

public class CharToString {

  public static void main(String[] args) {
    char c = 'b';
    String s = String.format("%c", c);
    
    System.out.println("String equivaluent of character '" + c + "' is " + s );
    
  }

}
String equivaluent of character 'b' is b

You might be interested in reading Convert Chat to Integer in Java

Reference

Translate ยป