You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么如下Java代码调用substring方法不会抛出IndexOutOfBoundsError?

Java substring方法运行逻辑说明

你给出的测试代码如下:

String s = "a";
String ss = s.substring(1);
System.out.println(ss.length());

运行不抛异常、输出0的结果完全符合JavaString类的方法设计规则,具体逻辑如下:

  • String.substring(int beginIndex)的入参合法范围为 0 ≤ beginIndex ≤ 字符串本身的长度,只有入参小于0、或者大于字符串长度时,才会抛出IndexOutOfBoundsException。
  • 当beginIndex恰好等于字符串长度时,方法会直接返回长度为0的空字符串,不会触发异常。
  • 示例中的字符串s = "a"长度为1,调用s.substring(1)时入参刚好等于字符串长度,符合合法入参要求,因此返回空字符串,最终输出长度为0。
  • 扩展说明:双参数重载方法substring(int beginIndex, int endIndex)也遵循同类规则,只要满足0 ≤ beginIndex ≤ endIndex ≤ 字符串长度就不会报错,当beginIndex == endIndex时同样返回空字符串。

内容的提问来源于stack exchange,提问作者user14603655

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:12:01