873
votes

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

12
Downvoted? Why would I ask such an easy question? Because Google lacks a really obvious search result for this question. By putting this here we'll change that.Landon Kuhn
i completely agree with your opinion. I up voted this to get rid of the negative vote. I firmly believe in making googling topics like this easier for everyone. =)prolink007
Did your research include reading the documentation of the String class?DJClayworth
@DJClayworth Most SO questions could be answered with RTFM, but that's not very helpful. Why not let people who find the question upvote it and let things take their course?beldaz
@PaulBellora Only that StackOverflow has become the first stop for research. If there is a StackOverlfow link in the first 10 Google Results I com here.Martin

12 Answers

664
votes

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.

247
votes

I've got of the following five six methods to do it.

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

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

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

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

// Method #5
// Although this approach seems very simple, 
// this is less efficient because the concatenation
// expands to a StringBuilder.
String concatBlankString = 'c' + "";

// Method #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.

Sources:

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

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
35
votes

Use the Character.toString() method like so:

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

Use any of the following:

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

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.

15
votes

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

4
votes

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.

4
votes

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();
2
votes

I am converting Char Array to String

Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);
1
votes
  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.

0
votes

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;
                }
            }
        }});