建議您運行在一個IDE和調試 步進入方法串碼和您的查詢就會回答
檢查子串方法的源代碼
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
這裏:
- 的開始索引爲8,
- 8是不小於0
- subLen = 0和不小於0
嘗試通過9到子,你會得到
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1875)
at com.iqp.standalone.Sample.main(Sample.java:14)
不,可以在字符串末尾開始子字符串,它只是給你空字符串'「」'(字符串長度爲0)。 –
檢查[Javadoc](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int))。 –
該文檔顯示「拋出:IndexOutOfBoundsException」 - 如果beginIndex爲負數或大於此String對象的長度。「您可以採取這種方式來表示嚴格較大。 'beginIndex'允許等於length(在你的例子中都是8)。 –