3

Suppose I want to convert a CharSequence to a String in Java.

Which option (1 or 2) is better and why?

CharSequence source = "some text";
String someText1 = (String)source; // 1
String someText2 = source.toString(); // 2
Didac Perez Parera
  • 3,734
  • 3
  • 52
  • 87

2 Answers2

9

The best option is behind Door #3:

String someText = String.valueOf(source);

Because that will handle the case where source is null.

user949300
  • 15,364
  • 7
  • 35
  • 66
  • 1
    Just a note, it will "handle" that case by setting the value of `someText` to the string `"null"` - which I personally don't think is very elegant, but at least it's easy to check for (as long as you aren't expecting the CharSequence to have the literal value of `"null"`, which I hope you aren't) – rook218 Jul 16 '21 at 13:35
2

#1 doesn't even work for CharSequence implementations other than String, so #2 is really your only option.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413