Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from CharSequence to String in Java [duplicate]

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
like image 253
Didac Perez Parera Avatar asked May 07 '26 09:05

Didac Perez Parera


2 Answers

The best option is behind Door #3:

String someText = String.valueOf(source);

Because that will handle the case where source is null.

like image 195
user949300 Avatar answered May 09 '26 00:05

user949300


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

like image 38
Louis Wasserman Avatar answered May 08 '26 23:05

Louis Wasserman