Search code examples
javastringsubstringsubsequence

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


String.subSequence() has the following javadoc:

Returns a new character sequence that is a subsequence of this sequence.

An invocation of this method of the form

str.subSequence(begin, end)

behaves in exactly the same way as the invocation

str.substring(begin, end) 

This method is defined so that the String class can implement the CharSequence interface.

Can anyone explain?


Solution

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