How can I convert a Java CharSequence
to a String
?
6 Answers
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.
-
@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
-
1By using the toString() method my CharSequence is displaying as, "[Ljava.lang.CharSequence;@26ae880a", not the text that was actually sent. toString() doesn't work.– AntonJul 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
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();
-
12You shouldn't make mistakes/make your code worse because others might have made a mistake.– LodewijkApr 18, 2013 at 2:03
-
10return new StringBuilder(charSequence).toString(); is a single liner equivalent. Sep 1, 2015 at 12:48
-
33THIS ANSWER IS WRONG The
CharSequence
interface explicitly definestoString()
- 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– earcamApr 16, 2016 at 14:34 -
4This 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 asList
orSet
, in particular theirequals()
andhashCode()
methods which will compile without overrides, but must be overridden according to the contract.– shmoselJul 29, 2016 at 20:37 -
4The 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.– fragorlAug 1, 2016 at 1:59
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.
-
17This actually just bit me today. if
charSequence
is null then the returned string will be"null"
and notnull
. Mar 5, 2018 at 20:31 -
-
2
-
1This 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
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
:
- Type Casting:
String string = (String) charSequence;
- Calling
toString()
:String string = charSequence.toString();
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.
-
new StringBuilder(charSequence).toString();
will through NullPointerException ifcharSequence
isnull
. Jan 24, 2022 at 18:51
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());
}
}
String.valueOf(charSequence)
. Here is the detailed answer