937

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

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Landon Kuhn
  • 76,451
  • 45
  • 104
  • 130
  • 218
    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 Nov 17 '11 at 18:40
  • 55
    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 Nov 17 '11 at 18:48
  • Your position is arguable (meta question?); I guess we can assume the downvote is for "lack of research". – Paul Bellora Nov 17 '11 at 18:51
  • 2
    I did do research. I had to click on a few search results and look at lengthy blog posts and ads. – Landon Kuhn Nov 17 '11 at 19:30
  • 4
    Did your research include reading the documentation of the String class? – DJClayworth Nov 17 '11 at 19:51
  • 17
    @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 May 11 '13 at 05:58
  • 12
    @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 Feb 13 '14 at 19:04
  • [How to Convert Character to String in Java](https://www.tutorialcup.com/java/convert-char-to-string-in-java.htm) – Rahul Gupta May 16 '21 at 17:22

13 Answers13

689

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
274

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
xagyg
  • 9,562
  • 2
  • 32
  • 29
WarFox
  • 4,933
  • 3
  • 28
  • 32
59

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
sactiw
  • 21,935
  • 4
  • 41
  • 28
34

Use any of the following:

String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";
Wayne
  • 59,728
  • 15
  • 131
  • 126
33

Use the Character.toString() method like so:

char mChar = 'l';
String s = Character.toString(mChar);
byxor
  • 5,930
  • 4
  • 27
  • 44
Tom
  • 2,973
  • 3
  • 28
  • 32
19

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.

Dmitriy Dumanskiy
  • 11,657
  • 9
  • 37
  • 57
18

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

Óscar López
  • 232,561
  • 37
  • 312
  • 386
5

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.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
4

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();
hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
2

I am converting Char Array to String

Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);
Py-Coder
  • 2,024
  • 1
  • 22
  • 28
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/15016514) – pczeus Jan 27 '17 at 05:13
  • I am Converting Char Array to String @pczeus – Py-Coder Jan 27 '17 at 14:23
1
  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.

Firzok Nadeem
  • 659
  • 6
  • 15
0

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;
                }
            }
        }});
zmicer
  • 172
  • 1
  • 4
-1

To convert a char to a String, you can use the String.valueOf method.

To convert a String to a char, you can use the String.charAt method.

char character = 'a';
String string = String.valueOf(character);
String string = "a";
char character = string.charAt(0);
Reilas
  • 3,297
  • 2
  • 4
  • 17