Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use String.subSequence method over String.subString?

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

like image 986
user3758749 Avatar asked Dec 07 '25 09:12

user3758749


2 Answers

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

like image 112
morgano Avatar answered Dec 09 '25 23:12

morgano


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.

like image 31
ajb Avatar answered Dec 09 '25 22:12

ajb