Belgi
Belgi

Reputation: 15082

How to convert CharSequence to String?

How can I convert a Java CharSequence to a String?

Upvotes: 254

Views: 195466

Answers (8)

Why not use Optional? This would handle nulls appropriately

String string = Optional.ofNullable(charSequence).map(CharSequence::toString).orElse(null);

Upvotes: 1

Martin Lemnian
Martin Lemnian

Reputation: 41

There is another solution.

As stated before charSequence.toString() is not null safe and

String.valueOf(charSequence) will produce a "null" if charSequence is null.

If this is not what you wanted you could use:

Objects.toString(charSequence, null). The second argument is the nullDefault.

This will do essentially:

  if(charSequence == null) {
    return null;
  }
  return String.valueOf(charSequence);

See https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#toString-java.lang.Object-java.lang.String-

Upvotes: 2

Minhas Kamal
Minhas Kamal

Reputation: 22196

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.

Upvotes: 19

Gaur 97
Gaur 97

Reputation: 93

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

Upvotes: 1

Arman Arshakyan
Arman Arshakyan

Reputation: 36

Also you can une Stringbuilder.

new StringBuilder(charSequence).toString();

Upvotes: 0

Abhishek Batra
Abhishek Batra

Reputation: 1599

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.

Upvotes: 33

fragorl
fragorl

Reputation: 1736

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

Upvotes: 93

Mike Samuel
Mike Samuel

Reputation: 120566

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.

Upvotes: 396

Related Questions