Java Convert char to String

The char data type stores a single 16-bit Unicode character, and String, also stores a sequence of characters. Moreover, you may need to carry out operations on individual char values by converting them to the String object for functions like concatenation, manipulation, or presentation.

Java has many ways to achieve these types of changes; each method is better fitting for specific situations and needs of your program.

Java Convert char to String

Let's explore some common techniques:

Using String.valueOf() method:

The String.valueOf() method converts non-string data types, including the char, to their string representation. It provides a direct way of transforming a char to a String, which fits the majority of the cases.

Let's see the simple example of converting char to String.

Output:

Converted From char to String is: a

Using Character.toString() method:

Character.ToString() is highly optimized for converting a char to a String but still ensures that the code is as readable as possible. Directly in it converts the char to a String object without hidden supply.

Let's see the simple code to convert char to String.

Output:

Converted from Char to String is: M

Using String.copyValueOf() method:

The String.copyValueOf() method is used to produce a new String which has the specified UTF-16 character sequence. It provides a different way of converting character into string mostly on array initialization.

Let's see the simple code to convert char to String.

Output:

Converted from Char to String is: Hello

Using Concatenation with Empty String (""):

This technique utilizes appended character concatenation to an empty string, casting it to a String. The simplicity is not immune to the possibility of being less efficient than some other methods, due to unnecessary string concatenation process.

Let's see the simple code to convert char to String.

Output:

Converted from Char to String is: a

Using String Constructor:

The technique involves the String class constructor that takes into account a char array. From the straightforward point of view, it involves new array object creation which may be causing the performance issue in Java for the single letter conversions.

Let's see the simple code to convert char to String.

CharToStringExample.java

Output:

Converted from Char to String is: a

Using StringBuilder or StringBuffer Class:

StringBuilder or StringBuffer class allows a String to be built from chars smoothly, and this is important in situations where dynamic string construction is involved. These classes have mutability features and become better while concatenating several characters.

Let's see the simple code to convert char to String.

CharToStringExample.java

Output:

Converted from Char to String is: a





Latest Courses