这个问题在这里已有答案:
我感到很困惑。我想使用str.substring(1),str必须至少有2个字符,否则应该有绑定索引。但是当我输入时,Java不会给出任何错误。为什么?
阅读Javadoc:
String java.lang.String.substring(int beginIndex)
返回一个字符串,该字符串是此字符串的子字符串。子字符串以指定索引处的字符开头,并延伸到此字符串的末尾。
抛出:
IndexOutOfBoundsException - 如果beginIndex为负或大于此String对象的长度。
你的beginIndex
等于String
的长度,因此不会抛出任何异常并返回空的String
。
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
使索引等于长度以返回空字符串是合法的。