java中字符串索引的边界
此代码java中字符串索引的边界,java,substring,indexoutofboundsexception,Java,Substring,Indexoutofboundsexception,此代码 public String a() { String x = "abc"; String y = x.substring(3,3); return y; //returns : "" } 工作时没有错误,但我认为该字符串没有第三个索引。据我所知,字符串的索引,如第一个字符是0索引,第二个字符是1索引,它是这样的。那么为什么不给我一个错误,如“OutOfBoundsException”?来自文档: IndexOutOfBoundsException-如果beginIndex为负数,则为
public String a() {
String x = "abc";
String y = x.substring(3,3);
return y; //returns : ""
}
工作时没有错误,但我认为该字符串没有第三个索引。据我所知,字符串的索引,如第一个字符是0索引,第二个字符是1索引,它是这样的。那么为什么不给我一个错误,如“OutOfBoundsException”?来自文档: IndexOutOfBoundsException-如果beginIndex为负数,则为endIndex 大于此字符串对象的长度,或beginIndex为 大于endIndex
这些条件都不满足。查看代码,您会发现它不满足异常要求
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);
}
公共字符串子字符串(int-beginIndex,int-endIndex){
如果(beginIndex<0){
抛出新的StringIndexOutOfBoundsException(beginIndex);
}
if(endIndex>value.length){
抛出新的StringIndexOutOfBoundsException(endIndex);
}
int SUBELN=endIndex-beginIndex;
如果(子项<0){
抛出新StringIndexOutOfBoundsException(SubCN);
}
返回((beginIndex==0)和(&(endIndex==value.length))?此
:新字符串(值、beginIndex、子项);
}