java为什么这些案例不返回IndexOutofBoundsException?
我最近偶然发现了这一点。为什么以下情况不返回IndexOutofBoundsException
public static void main(String[] args) {
String str = "String";
System.out.print(str.substring(0, 0));
}
public static void main(String[] args) {
String str = "String";
System.out.print(str.substring(str.length()));
}
我一直被告知这一点。子字符串(inti,intk)返回从索引i到k-1的子字符串。在第一种情况下,子字符串不是从索引0到-1吗?为什么这不会产生越界错误?我也有同样的问题。长度()的情况下,以及
# 1 楼答案
从Java 8 API开始:
是阴性吗?不,是0
endIndex
是否大于字符串的长度?不,0<;6.beginIndex
比endIndex
大吗?不,他们都是0你为什么期望它抛出异常
length()
从不扔# 2 楼答案
看看substring javadoc:
因此,
"String".substring(0, 0)
只返回空字符串""
看看length javadoc:
因此
"String".length()
返回5
# 3 楼答案
String
JavaDoc表示IndexOutOfBoundsException
将被抛出,如果:您的示例不符合任何这些标准,因此不会引发异常。如果开始索引和结束索引相等,结果总是得到一个空的
String
对于第二个例子,我不太确定你的问题是什么
.length()
只返回String
包含的字符数。在上面的示例中,它只返回int
6