How to convert a char to a String?

Landon Kuhn picture Landon Kuhn · Nov 17, 2011 · Viewed 1.1M times · Source

I have a char and I need a String. How do I convert from one to the other?

Answer

Paul Bellora picture Paul Bellora · Nov 17, 2011

You can use Character.toString(char). Note that this method simply returns a call to String.valueOf(char), which also works.

As others have noted, string concatenation works as a shortcut as well:

String s = "" + 's';

But this compiles down to:

String s = new StringBuilder().append("").append('s').toString();

which is less efficient because the StringBuilder is backed by a char[] (over-allocated by StringBuilder() to 16), only for that array to be defensively copied by the resulting String.

String.valueOf(char) "gets in the back door" by wrapping the char in a single-element array and passing it to the package private constructor String(char[], boolean), which avoids the array copy.