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

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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();
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.