"A".substring(1)因为字符串的长度只有1,而且是从0开始编号的。
还是去看看源代码吧
public String substring(int beginIndex) {
return substring(beginIndex, count);
}
其中的count没有悬念,是字符串的字符长度,对于我们的例子,长度就是1.
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) { // 注意看这里
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex,
endIndex - beginIndex, value);
}
青年人网站提示: 系统是起始的位置如果大于结束的位置,此处结束位置就是字符串的长度1
而我们写的起始位置等于字符串长度,没有大于结束位置,所以不会报异常。
如果写成
"A".substring(2)
则由于超过了字符串的长度1,报
StringIndexOutOfBoundsException
责任编辑:小草