为什么这个布尔表达式无法翻转?

Max*_*Max 1 java

这就是我为编码棒项目写的东西.由于某种原因,它说这种方式不起作用,但如果我翻转它,它的工作原理.这是为什么?当它输入少于3个字符的内容时,它会根据codingbat获得错误消息.

// Given a string, return a new string where "not " has been added to the front. 
// However, if the string already begins with "not", return the string unchanged. 
// Note: use .equals() to compare 2 strings. 

// notString("candy") ? "not candy"
// notString("x") ? "not x"
// notString("not bad") ? "not bad"

        public String notString(String str) {
                  String m;
          if ( str.substring (0,3).equalsIgnoreCase("not") && str.length () >= 3 ) // this line doesn't work in it's current state 
          // but works if I flip the two boolean expressions over the &&

                    m = str;
          else {
                    m = "not " + str;
                }
       return m;
Run Code Online (Sandbox Code Playgroud)

rge*_*man 6

如果字符串的长度不是至少为3,那么str.subtring(0, 3)将失败IndexOutOfBoundsException.

翻转时工作的原因称为短路评估.翻转:

if ( str.length() >= 3 && str.substring (0,3).equalsIgnoreCase("not") )
Run Code Online (Sandbox Code Playgroud)

评估第一个条件.如果它小于3,则Java知道整个条件是false,因为false && anythingfalse.它不会评估另一个表达式,因为它不必评估它.这IndexOutOfBoundsException不是出于这个原因.

JLS,15.23节这个会谈:

条件和运算符&&类似于&(§15.22.2),但仅在其左侧操作数的值为真时才计算其右侧操作数.

此外,逻辑或运算符(条件或运算符)的||工作方式类似.如果左侧操作数是false(JLS Section 15.24),它将仅评估其右侧操作数.