辅导:A.substring(1)不报异常的分析
来源:优易学  2011-10-22 11:48:18   【优易学:中国教育考试门户网】   资料下载   IT书店
  "A".substring(1)因为字符串的长度只有1,而且是从0开始编号的。
  还是去看看源代码吧
  public String substring(int beginIndex) {
  return substring(beginIndex, count);
  }
  其中的count没有悬念,是字符串的字符长度,对于我们的例子,长度就是1.  
  public String substring(int beginIndex, int endIndex) {
  if (beginIndex < 0) {
  throw new StringIndexOutOfBoundsException(beginIndex);
  }
  if (endIndex > count) {
  throw new StringIndexOutOfBoundsException(endIndex);
  }
  if (beginIndex > endIndex) { // 注意看这里
  throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
  }
  return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex,
  endIndex - beginIndex, value);
  }
  青年人网站提示: 系统是起始的位置如果大于结束的位置,此处结束位置就是字符串的长度1
  而我们写的起始位置等于字符串长度,没有大于结束位置,所以不会报异常。
  如果写成
  "A".substring(2)
  则由于超过了字符串的长度1,报
  StringIndexOutOfBoundsException

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训