Convert a char to a String in Java in 5 different ways

In this post, we will see how to convert a primitive char value to its equivalent String in Java.


Converting a char to its equivalent String is very simple and straightforward in Java. We can use any of following 5 methods to convert a char to a String in Java.


1. String.valueOf(char)

The standard approach to convert a char to a String in Java is to use String.valueOf(char) method which returns the string representation of specified char argument.

String.valueOf(char) proves to be be most efficient method for converting char to String. It basically wraps the specified char in a single-element character array and pass it to String constructor as evident from below snipet.

We can also do something similar and wrap the given char in a character array and pass it to String.valueOf(char[]) function as shown below:

String.valueOf(char[]), internally calls the string constructor which in turn uses Arrays.copyOf() method to set the String value from char array.


2. Character.toString(char)

We can also use Character.toString(char) which is effectively same as String.valueOf(char) as Character.toString(char) simply returns a call to String.valueOf(char).


3. String concatenation

We can concatenate the given char with an empty String, which will convert a char to a String object.

This looks like pretty simple approach, but this is least efficient method because the string concatenation compiles down to:


4. Using String Constructor

We have seen that String.valueOf() uses an single-element character array to wrap the specified character and then pass it to the String constructor. We can directly call the String constructor as shown below:


5. String.format()

Finally, we can use String.format() method that returns a formatted string from the specified char arguments.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of