This question already has answers here:
Substring method in String class reaches the index it isn't supposed to [duplicate]
                                
                                    (4个答案)
                                
                        
                                3年前关闭。
            
                    
我有以下表达:

  String y = new String("a") + "b".substring(1,1) + "c".concat("d").toUpperCase();


该代码编译,并成功打印“ aCD”。我的问题是,为什么?

根据JLS,在评估表达式之前,应从左至右评估操作数。这意味着“ b” .substring(1,1)应该抛出IndexOutOfBoundsException。相反,它似乎只是抛弃了价值。

Java在做什么会导致“ aCD”的结果?

注意-我永远不会这样做-我只是想满足好奇心。

最佳答案

它不应引发异常,因为:


beginIndex不是负数。
endIndex不大于String的长度。
beginIndex不得大于endIndex。


为了显示

"b" has a length of 1, a begin index of 0.

"b".substring(1,1);



beginIndex为“ 1”,并且不为负。
endIndex“ 1”不大于字符串“ 1”的长度。
beginIndex“ 1”不大于endIndex“ 1”。


我完全同意该代码是愚蠢的,因为它可以保证返回字符串“”;但是,在许多情况下都需要计算这些索引,并且在某些情况下,允许返回空字符串而不是异常是很有意义的。

10-07 16:41