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
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
The best option is behind Door #3:
String someText = String.valueOf(source);
Because that will handle the case where source
is null.
#1 doesn't even work for CharSequence
implementations other than String
, so #2 is really your only option.