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

code511788465541441 picture code511788465541441 · Mar 19, 2013 · Viewed 47.6k times · Source

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?

Answer

Amar picture Amar · Mar 19, 2013

Subsequence

Subsequence is a generalisation of substring, suffix, and prefix. Finding the longest string which is a subsequence of two or more strings is known as the longest common subsequence problem.

Example: The string "anna" is a subsequence of the string "banana":

banana
 || ||
 an na

Substring

A substring of a string is a prefix of a suffix of the string, and equivalently a suffix of a prefix. If one string is a substring of another, it is also a subsequence, which is a more general concept.

Example: The string "ana" is a substring (and subsequence) of banana at two different offsets:

banana
 |||||
 ana||
   |||
   ana

Read more here.

But as far as Java is concerned, there isn't any difference in their use as stated clearly in the javadoc. Also as it's stated in there, the method subSequence has only been implemented in class String so as to keep it compliant with the CharSequence interface. And this method's name is indeed just a misnomer.