240812-String的substring(int beginIndex)方法的beginIndex可以是String的长度吗?

23 阅读1分钟

答案

可以!!!

public static void main(String[] args) {
    System.out.println("12".substring(2)); // 结果:""
}
// String的substring源码
public String substring(int beginIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    int subLen = value.length - beginIndex;
    if (subLen < 0) { // 可以看到,只有beginIndex>value.length才抛异常,相等不抛异常
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}