[java] How to convert a char to a String?

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

This question is related to java string char type-conversion

The answer is


Use the Character.toString() method like so:

char mChar = 'l';
String s = Character.toString(mChar);

I've tried the suggestions but ended up implementing it as follows

editView.setFilters(new InputFilter[]{new InputFilter()
        {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend)
            {
                String prefix = "http://";

                //make sure our prefix is visible
                String destination = dest.toString();

                //Check If we already have our prefix - make sure it doesn't
                //get deleted
                if (destination.startsWith(prefix) && (dstart <= prefix.length() - 1))
                {
                    //Yep - our prefix gets modified - try preventing it.
                    int newEnd = (dend >= prefix.length()) ? dend : prefix.length();

                    SpannableStringBuilder builder = new SpannableStringBuilder(
                            destination.substring(dstart, newEnd));
                    builder.append(source);
                    if (source instanceof Spanned)
                    {
                        TextUtils.copySpansFrom(
                                (Spanned) source, 0, source.length(), null, builder, newEnd);
                    }

                    return builder;
                }
                else
                {
                    //Accept original replacement (by returning null)
                    return null;
                }
            }
        }});

Below are various ways to convert to char c to String s (in decreasing order of speed and efficiency)

char c = 'a';
String s = String.valueOf(c);             // fastest + memory efficient
String s = Character.toString(c);
String s = new String(new char[]{c});
String s = String.valueOf(new char[]{c});
String s = new Character(c).toString();
String s = "" + c;                        // slowest + memory inefficient

Here are a few methods, in no particular order:

char c = 'c';

String s = Character.toString(c); // Most efficient way

s = new Character(c).toString(); // Same as above except new Character objects needs to be garbage-collected

s = c + ""; // Least efficient and most memory-inefficient, but common amongst beginners because of its simplicity

s = String.valueOf(c); // Also quite common

s = String.format("%c", c); // Not common

Formatter formatter = new Formatter();
s = formatter.format("%c", c).toString(); // Same as above
formatter.close();

Use any of the following:

String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";

  char vIn = 'A';
  String vOut = Character.toString(vIn);

For these types of conversion, I have site bookmarked called https://www.converttypes.com/ It helps me quickly get the conversion code for most of the languages I use.


I am converting Char Array to String

Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);

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.


As @WarFox stated - there are 6 methods to convert char to string. However, the fastest one would be via concatenation, despite answers above stating that it is String.valueOf. Here is benchmark that proves that:

@BenchmarkMode(Mode.Throughput)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
public class CharToStringConversion {

    private char c = 'c';

    @Benchmark
    public String stringValueOf() {
        return String.valueOf(c);
    }

    @Benchmark
    public String stringValueOfCharArray() {
        return String.valueOf(new char[]{c});
    }

    @Benchmark
    public String characterToString() {
        return Character.toString(c);
    }

    @Benchmark
    public String characterObjectToString() {
        return new Character(c).toString();
    }

    @Benchmark
    public String concatBlankStringPre() {
        return c + "";
    }

    @Benchmark
    public String concatBlankStringPost() {
        return "" + c;
    }

    @Benchmark
    public String fromCharArray() {
        return new String(new char[]{c});
    }
}

And result:

Benchmark                                        Mode  Cnt       Score      Error  Units
CharToStringConversion.characterObjectToString  thrpt   10   82132.021 ± 6841.497  ops/s
CharToStringConversion.characterToString        thrpt   10  118232.069 ± 8242.847  ops/s
CharToStringConversion.concatBlankStringPost    thrpt   10  136960.733 ± 9779.938  ops/s
CharToStringConversion.concatBlankStringPre     thrpt   10  137244.446 ± 9113.373  ops/s
CharToStringConversion.fromCharArray            thrpt   10   85464.842 ± 3127.211  ops/s
CharToStringConversion.stringValueOf            thrpt   10  119281.976 ± 7053.832  ops/s
CharToStringConversion.stringValueOfCharArray   thrpt   10   86563.837 ± 6436.527  ops/s

As you can see, the fastest one would be c + "" or "" + c;

VM version: JDK 1.8.0_131, VM 25.131-b11

This performance difference is due to -XX:+OptimizeStringConcat optimization. You can read about it here.


We have various ways to convert a char to String. One way is to make use of static method toString() in Character class:

char ch = 'I'; 
String str1 = Character.toString(ch);

Actually this toString method internally makes use of valueOf method from String class which makes use of char array:

public static String toString(char c) {
    return String.valueOf(c);
}

So second way is to use this directly:

String str2 = String.valueOf(ch);

This valueOf method in String class makes use of char array:

public static String valueOf(char c) {
        char data[] = {c};
        return new String(data, true);
}

So the third way is to make use of an anonymous array to wrap a single character and then passing it to String constructor:

String str4 = new String(new char[]{ch});

The fourth way is to make use of concatenation:

String str3 = "" + ch;

This will actually make use of append method from StringBuilder class which is actually preferred when we are doing concatenation in a loop.


Try this: Character.toString(aChar) or just this: aChar + ""


Nice question. I've got of the following five 6 methods to do it.

// #1
String stringValueOf = String.valueOf('c'); // most efficient

// #2
String stringValueOfCharArray = String.valueOf(new char[]{x});

// #3
String characterToString = Character.toString('c');

// #4
String characterObjectToString = new Character('c').toString();

// #5
   // Although this method seems very simple, 
   // this is less efficient because the concatenation
   // expands to new StringBuilder().append(x).append("").toString();
String concatBlankString = 'c' + "";

// #6
String fromCharArray = new String(new char[]{x});

Note: Character.toString(char) returns String.valueOf(char). So effectively both are same.

String.valueOf(char[] value) invokes new String(char[] value), which in turn sets the value char array.

public String(char value[]) {
    this.value = Arrays.copyOf(value, value.length);
}

On the other hand String.valueOf(char value) invokes the following package private constructor.

String(char[] value, boolean share) {
    // assert share : "unshared not supported";
    this.value = value;
}

Source code from String.java in Java 8 source code

Hence String.valueOf(char) seems to be most efficient method, in terms of both memory and speed, for converting char to String.

  1. How to convert primitive char to String in Java
  2. How to convert Char to String in Java with Example

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to char

How can I convert a char to int in Java? C# - How to convert string to char? How to take character input in java Char Comparison in C Convert Char to String in C cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' How to get the real and total length of char * (char array)? Why is conversion from string constant to 'char*' valid in C but invalid in C++ char *array and char array[] C++ - How to append a char to char*?

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift