246

How can I convert a Java CharSequence to a String?

1

6 Answers 6

389

By invoking its toString() method.

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

9
  • @TheOnlyAnil, does calling setText(CharSequence) not do what you need? May 4, 2015 at 20:31
  • 1
    @TheOnlyAnil, maybe you should ask that as a question. Comments on an answer to a tangentially related question are not a good place to try and tease out your requirements. May 5, 2015 at 14:38
  • 1
    By using the toString() method my CharSequence is displaying as, "[Ljava.lang.CharSequence;@26ae880a", not the text that was actually sent. toString() doesn't work.
    – Anton
    Jul 25, 2018 at 12:41
  • 1
    @WillByers that output looks like the toString of a CharSequence array, not a CharSequence. Jul 25, 2018 at 13:45
  • 1
    @Hibbem someone else did it for you ;-)
    – logi-kal
    Jan 28, 2021 at 11:06
92

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
23
  • 12
    You shouldn't make mistakes/make your code worse because others might have made a mistake.
    – Lodewijk
    Apr 18, 2013 at 2:03
  • 10
    return new StringBuilder(charSequence).toString(); is a single liner equivalent. Sep 1, 2015 at 12:48
  • 33
    THIS ANSWER IS WRONG The CharSequence interface explicitly defines toString() - the implementor won't have missed this. The javadoc states "Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence" since inception in 1.4. People, please verify what you upvote
    – earcam
    Apr 16, 2016 at 14:34
  • 4
    This is silly. If you don't trust the implementer to follow the contract, all bets are off. Passing it as a parameter to StringBuilder could just as well fail to do what you expect. The same goes for any other interface, such as List or Set, in particular their equals() and hashCode() methods which will compile without overrides, but must be overridden according to the contract.
    – shmosel
    Jul 29, 2016 at 20:37
  • 4
    The fact that the interface does this is arguably a poor decision in that regard, and my answer simply highlights that this is an easier than normal place for human error to occur.
    – fragorl
    Aug 1, 2016 at 1:59
30

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

4
  • 17
    This actually just bit me today. if charSequence is null then the returned string will be "null" and not null. Mar 5, 2018 at 20:31
  • Oh. Makes sense. I will remove this answer Mar 5, 2018 at 20:38
  • 2
    I think this is perfect for some cases. Jan 4, 2019 at 16:08
  • 1
    This is quite same as charSequence.toString() looking at the definition in libcore/ojluni/src/main/java/java/lang/String.java public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } Jul 20, 2020 at 10:12
14

The Safest Way

String string = String.valueOf(charSequence);

Let's Dive Deep

There are 3 common ways that we can try to convert a CharSequence to String:

  1. Type Casting: String string = (String) charSequence;
  2. Calling toString(): String string = charSequence.toString();
  3. String.valueOf() Method: String string = String.valueOf(charSequence);

And if we run these where CharSequence charSequence = "a simple string"; then all 3 of them will produce the expected result.

The problem happens when we are not sure about the nature of the CharSequence. In fact, CharSequence is an interface that several other classes implement, like- String, CharBuffer, StringBuffer, etc. So, converting a String to a CharSequence is a straightforward assignment operation, no casting or anything is required. But, for the opposite, Upcasting, it is not true.

If we are sure that the CharSequence is actually an object of String, only then we can use option 1- Type Casting. Otherwise, we will get a ClassCastException. Option 2 and 3 are safe in this case.

On the other side, if the CharSequence is null then option 2, calling toString(), will give a NullPointerException.

Now internally, String.valueOf() method calls the toString() method after doing a null check. So, it is the safest way. JavaDoc:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.


Please be aware: If CharSequence is null then String.valueOf() method return the string- "null", not null value.

1
  • new StringBuilder(charSequence).toString(); will through NullPointerException if charSequence is null. Jan 24, 2022 at 18:51
1

If you want to convert an array of CharSequence, You can simply do this and can also be store it in a String[] variable.

CharSequence[] textMsgs = (CharSequence[])sbm.getNotification().extras.get(Notification.EXTRA_TEXT_LINES);
if (textMsgs != null) {
   for (CharSequence msg : textMsgs) {
       Log.e("Msg", msg.toString());
   }
}
0

Also you can une Stringbuilder.

new StringBuilder(charSequence).toString();

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.