323

How to convert String to CharSequence in Java?

Daksh Gargas
  • 3,498
  • 2
  • 23
  • 37
  • 26
    The question is kind of non sensical. Converting a String to a CharSequence is like converting a flute to a musical instrument. A String already is a CharSequence. The String class implements the CharSequence interface. – Jeff Scott Brown May 22 '14 at 21:29
  • 4
    The OP's confusion might stem from not knowing what it means to [program to an interface](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Raedwald Nov 14 '14 at 14:10
  • 14
    @JeffScottBrown the question actually makes sense, it's a legitimate wonder to anyone reading through the Android or Java doc and missing the detail that CharSequence is not a class. Your comment helped me, but if the question had not been worded the way it is, i wouldn't have found it and have spent more time looking for an answer than it's really worth ;) – Kheldar Mar 12 '15 at 14:42
  • I came to this question in the context of a groovy Problem: `Exception groovy.lang.MissingMethodException: No signature of method: static java.util.regex.Pattern.matcher() is applicable for argument types: (java.lang.String)` – BlackEye May 12 '15 at 13:41
  • Here's how I'd advice @JeffScottBrown to reword his comment- "The String class implements (IS-A) the CharSequence interface so you can pass in a String in place of a CharSequence. It's like how you could refer to a flute as a musical instrument because a flute IS-A musical instrument" – Vighnesh Jul 13 '17 at 00:42

6 Answers6

302

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.

Ruthwik
  • 545
  • 1
  • 8
  • 14
João Silva
  • 89,303
  • 29
  • 152
  • 158
  • 16
    Except that you can't assign a `CharSequence` to a `String` without an explicit cast. – gustafc Sep 08 '09 at 06:26
  • 1
    Fixed the example, thanks. I meant the other way around, i.e., assign a `String` to a `CharSequence`. – João Silva Sep 09 '09 at 00:24
  • 1
    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 Oct 16 '10 at 10:41
  • 4
    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. – João Silva Oct 16 '10 at 12:06
  • 7
    This is not the answer. Question is String -> to -> CharSequence. Answer is reverse. – trante Nov 08 '13 at 21:39
  • 4
    This answers both. Poster first trivially resolves the String -> CharSequence problem by explaining that a String IS a CharSequence. Then poster answers how to go from CharSequence to String. – Alex A. Nov 08 '13 at 23:05
  • Okay I just wrote `String.join(", ", () -> new Iterator...)` and it errors **argument mismatch**; _bad return type in lambda expression_, `Iterator` _cannot be converted to_ `Iterator`, so I don't think String is a CharSequence all the time – theonlygusti Jun 19 '23 at 20:51
81

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.

icza
  • 389,944
  • 63
  • 907
  • 827
13

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";

krmanish007
  • 6,749
  • 16
  • 58
  • 100
4

You can use

CharSequence[] cs = String[] {"String to CharSequence"};
Lucas Fialho
  • 57
  • 1
  • 1
  • 10
    Welcome to Stack Overflow Lucas. Please provide more explanation than a code snippet. It may be obvious for us, but help others letting them know why this code answer the question. – Jean-Rémy Revy Sep 22 '14 at 20:14
  • Wrapping a string into an array doesn't help making a point that String is a CharSequence (and hence that array of CharSequence is array of String). – tishma May 15 '17 at 08:33
  • 1
    CharSequence[] cs = new CharSequence[] {"String to CharSequence"}; – avez raj Dec 13 '17 at 14:53
3

That's a good question! You may get into troubles if you invoke API that uses generics and want to assign or return that result with a different subtype of the generic type. Java 8 helps to transform:

    List<String> input = new LinkedList<>(Arrays.asList("a", "b", "c"));
    List<CharSequence> result;
    
//    result = input; // <-- Type mismatch: cannot convert from List<String> to List<CharSequence>
    result = input.stream().collect(Collectors.toList());
    
    System.out.println(result);
PAX
  • 1,056
  • 15
  • 33
2

Attempting to provide some (possible) context for OP's question by posting my own trouble. I'm working in Scala, but the error messages I'm getting all reference Java types, and the error message reads a lot like the compiler complaining that CharSequence is not a String. I confirmed in the source code that String implements the CharSequence interface, but the error message draws attention to the difference between String and CharSequence while hiding the real source of the trouble:

scala> cols
res8: Iterable[String] = List(Item, a, b)

scala> val header = String.join(",", cols)
<console>:13: error: overloaded method value join with alternatives:
  (x$1: CharSequence,x$2: java.lang.Iterable[_ <: CharSequence])String <and>
  (x$1: CharSequence,x$2: CharSequence*)String
 cannot be applied to (String, Iterable[String])
       val header = String.join(",", cols)

I was able to fix this problem with the realization that the problem wasn't String / CharSequence, but rather a mismatch between java.lang.Iterable and Scala's built-in Iterable.

scala> val header = String.join(",", coll: _*)
header: String = Item,a,b

My particular problem can also be solved via the answers at Scala: join an iterable of strings

In summary, OP and others who come across similar problems should parse the error messages very closely and see what other type conversions might be involved.

Sarah Messer
  • 3,592
  • 1
  • 26
  • 43
  • I had another similar error (in scala) trying to use the `String.replace` method with argument types `(Char)`, but it needs two arguments, so I added the empty String as the second argument (which I assumed was the default) and converted the first argument to String (since it needed to match either both `Char` or `CharSequence`. So, mine was another example of closely reading the argument type options vs. my own method call. – combinatorist May 16 '23 at 18:15