What is the difference between String.subString() and String.subSequence()

Using str.subSequence(begin, end) returns a CharSequence which is a read-only form of the string represented as a sequence of chars. For example:

String string = "Hello";
CharSequence subSequence = string.subSequence(0, 5);

It’s read only in the sense that you can’t change the chars within the CharSequence without instantiating a new instance of a CharSequence.

If you have to use str.subSequence(begin, end), you can cast the result to a String:

String string = "Hello";
String subSequence = (String) string.subSequence(0, 5);

and use all the normal String operators like subSequence += " World";

Leave a Comment