views:

6926

answers:

1

how to convert string to Charsequence in JAVA...????

+15  A: 

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) { 
  System.out.println(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.

Hope it helps.

JG
Except that you can't assign a `CharSequence` to a `String` without an explicit cast.
gustafc
Fixed the example, thanks. I meant the other way around, i.e., assign a `String` to a `CharSequence`.
JG
I'm confused by this code "CharSequence cs = "string"; ". How can we instantiate a CharSequence? Isn't that an Interface? (Sorry I'm still learning Java).
Mugen
You are correct. It is indeed an interface. However, that code does not instantiate a `CharSequence`. It simply assigns an instance of `String` to a `CharSequence` variable, and since `String` implements the `CharSequence` interface, the code works.
JG