28

What's the most efficient way to pass a single char to a method expecting a CharSequence?

This is what I've got:

textView.setText(new String(new char[] {c} ));

According to the answers given here, this is a sensible way of doing it where the input is a character array. I was wondering if there was a sneaky shortcut I could apply in the single-char case.

7 Answers 7

51
textView.setText(String.valueOf(c))
0
13

Looking at the implementation of the Character.toString(char c) method reveals that they use almost the same code you use:

  public String toString() {
       char buf[] = {value};
       return String.valueOf(buf);
  }

For readability, you should just use Character.toString( c ).

Another efficient way would probably be

new StringBuilder(1).append(c);

It's definitely more efficient that using the + operator because, according to the javadoc:

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method

1
  • 1
    Thanks for the explanation. I'm going with the accepted answer as I suspect the String class probably has a built-in table of single-character Strings to support the valueOf() functionality efficiently. Jul 6, 2011 at 21:30
4

The most compact CharSequence you can get when you have a handful of chars is the CharBuffer. To initialize this with your char value:

CharBuffer.wrap(new char[]{c});

That being said, using Strings is a fair bit more readable and easy to work with.

3

Shorthand, as in fewest typed characters possible:

c+""; // where c is a char

In full:

textView.setText(c+"");
2

A solution without concatenation is this:

Character.valueOf(c).toString();
1
char c = 'y';
textView.setText(""+c);
-1

Adding to an answer mentioned above (link), adding an example to make things clearer

char c = 'a';
CharSequence cs = String.valueOf(c);
3
  • 1
    stackoverflow.com/a/6603135/2227743
    – Eric Aya
    Nov 30, 2021 at 10:13
  • @EricAya the answer you mention uses textView and setText whose meaning was not clear to me. Hence I made this example, just to make it clearer. I wanted to do this as a comment to original answer only, but I did not have enough reputation. Let me just mention credit to the original answer Nov 30, 2021 at 10:57
  • I understand your point of view. Still, String.valueOf(c) is the solution to OP's question, and it has already been suggested in the other answer. No need to post it again in my opinion.
    – Eric Aya
    Nov 30, 2021 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.