Because the subSequence()
methods returns a String
object at runtime and not a StringBuilder
object. As per the documentation of StringBuilder#subSequence()
Returns a new character sequence that is a subsequence of this sequence.
An invocation of this method of the form
sb.subSequence(begin, end)
behaves in exactly the same way as the invocation
sb.substring(begin, end)
If you go through the code here :
public CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
And if you see the code for substring()
:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
It returns a String
, since String
implements CharSequence
interface the return type of subSequence()
can be that of CharSequence
, but the internally it works with String
. And you cannot cast String
to StringBuilder
.