3

I know subSequence returns a charSequence which is a read-only. Also, String class implements CharSequence. subString returns a String.

But, amongst subsequence and substring, when and which one to prefer

user3758749
  • 117
  • 1
  • 2
  • 6

3 Answers3

3

From the API javadoc:

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)

And also:

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

so, it is appropriate to use subSequence when you are working with objects of type CharSequence rather than String

morgano
  • 17,210
  • 10
  • 45
  • 56
1

You can always use substring. The javadoc says the two have the same behavior. Although subSequence returns a CharSequence and substring returns a String, String implements CharSequence, thus you can always use substring in contexts where a CharSequence is required.

According to the javadoc, subSequence is there because it has to be, in order to implement a method defined in CharSequence. Since it's there because it's required and not particularly because there's a reason to use it, I don't see any reason to use it if you have a String.

ajb
  • 31,309
  • 3
  • 58
  • 84
1

Here is a snippet from java.util.regex.Pattern.split where String.subSequence will be used if a String is passed as input arg:

    public String[] split(CharSequence input, int limit) {
...
                String match = input.subSequence(index, m.start()).toString();
...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275