So I read this answer and this answer on the differences between subSequence() and subString() and I understand that the only difference between the two is the return type. In fact, subSequence() calls subString() under the hood.
In addition, this article on subSequence states at the end that:
There is no benefit in using
subSequencemethod, ideally you should always use Stringsubstringmethod.
Is there really no benefit to using subSequence()? If so, why has it been introduced? If there is a benefit, what is it and what known uses are for it?
There's the benefit of abstraction when that's applicable to a program. As an example:
public CharSequence getPrefix(CharSequence cs) {
return cs.subSequence(0, 1);
}
And this can be called any CharSequence instance (String, StringBuilder, StringBuffer, etc.):
CharSequence cs = "John";
getPrefix("Name");
cs = new StringBuilder("James");
getPrefix(cs);
Normal applications hardly make use of the CharSequence interface, but that's applicable in some cases (libraries in particular).
It doesn't make much sense to write:
CharSequence sub = stringObject.subSequence(0, 1);
Because one normally expects a String-typed substring, but a framework may prefer to use CharSequence in its API, instead of String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With