"A".substring(1)不报异常的分析

今天收到网友 不懂装懂 的来信

您好,讨论个问题
我看到代码"A".substring(1);我第一眼觉得应该越界,因为我基础不好,但是结果没有问题,是个空,我想请您指点迷津

我第一眼也是有问题,因为字符串的长度只有1,而且是从0开始编号的。

还是去看看源代码吧
  1. public String substring(int beginIndex) {
  2.     return substring(beginIndex, count);
  3. }
其中的count没有悬念,是字符串的字符长度,对于我们的例子,长度就是1.

  1.   public String substring(int beginIndex, int endIndex) {
  2.     if (beginIndex < 0) {
  3.       throw new StringIndexOutOfBoundsException(beginIndex);
  4.     }
  5.     if (endIndex > count) {
  6.       throw new StringIndexOutOfBoundsException(endIndex);
  7.     }
  8.     if (beginIndex > endIndex) { // 注意看这里
  9.       throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
  10.     }
  11.     return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex,
  12.         endIndex - beginIndex, value);
  13.   }
可见,系统是起始的位置如果大于结束的位置,此处结束位置就是字符串的长度1
而我们写的起始位置等于字符串长度,没有大于结束位置,所以不会报异常。

如果写成
  1. "A".substring(2)
则由于超过了字符串的长度1,报

StringIndexOutOfBoundsException


原文地址:http://www.java2000.net/p10866
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值