How to convert a String to CharSequence? – Dev

The best answers to the question “How to convert a String to CharSequence?” in the category Dev.


How to convert String to CharSequence in Java?


Straight answer:

String s = "Hello World!";

// String => CharSequence conversion:

CharSequence cs = s;  // String is already a CharSequence

CharSequence is an interface, and the String class implements CharSequence.


Since String IS-A CharSequence, you can pass a String wherever you need a CharSequence, or assign a String to a CharSequence:

CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"

public void foo(CharSequence cs) { 

If you want to convert a CharSequence to a String, just use the toString method that must be implemented by every concrete implementation of CharSequence.


You can use

CharSequence[] cs = String[] {"String to CharSequence"};


CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.

So, just as you use InterfaceName i = new ItsImplementation(), you can use CharSequence cs = new String("string") or simply CharSequence cs = "string";