简体   繁体   中英

Java: weird behavior of conditional operator

I have a very simple java class to solve Decode ways using recursive approach. I am seeing this weird behavior of conditional operator,

package decodeways;

public class Solution {
  public static void main(String[] args) {
    System.out.println(numDecodings("1456"));
  }
  
  public static int numDecodings(String s) {
    if(s.length()>0 && s.charAt(0)=='0') 
      return 0;
    if(s.length()==0) return 1;
    if(s.length()==1)
      return 1;
    
    int num1 = s.charAt(0)-'0';
    int num2 = s.charAt(1)-'0';
    int one = numDecodings(s.substring(1));
    int two = s.length()>1?numDecodings(s.substring(2)):0;
    int res = one 
        + num1<3 && num2<7 ? two:0;
    return res;
  }
}

if I put a parentheses, (num1<3 && num2<7? two:0) then everything is well and good but if I remove the parentheses, then getting incorrect results.

during the process of debugging, one will be computed to 1 and two will be computed to 1 and res will be 1 as well with parentheses but without it, the computed result of res will be 0 (screnshot attached) which is the source of error. 在此处输入图像描述 I am aware of the operator precedence in java, but in this situation I can't figure out why it shows incorrect behavior, because in the below code:

int res = one 
        + num1<3 && num2<7 ? two:0;

one + num1<3 is illegal So, java is intelligent enough to not confuse between (one + num1<3) and (num2<7? two:0) to be consider separately. So, as per my understanding the only legal observable behavior for java compiler is to automatically consider num1<3 && num2<7? two:0 num1<3 && num2<7? two:0 as an atomic operation(Please correct me if I am wrong), irrespective of parentheses is available or not.

Please guide me to have a better understanding.

Thanks.

int res = one 
        + num1<3 && num2<7 ? two:0;

is equivalent to

int res = (((one + num1) < 3) && (num2 < 7)) ? two : 0;

Everything before ? is included in the boolean expression, since the ternary/conditional operator has the lowest precedence here (not including the assignment operator) and + has the highest.

The order goes something like:

  • + , so one + num1 is put together first
  • < , so now there's (one + num1) < 3 and num2 < 7
  • && , after which you have ((one + num1) < 3) && (num2 < 7)
  • and finally ?:

You seem to be expecting the newline to make the compiler think one and num1<3 && num2<7? two:0 num1<3 && num2<7? two:0 are separate, but it actually just ignores all whitespace. Putting the parentheses there is the only way to make sure one is added to the whatever the conditional operator evaluates to.

int res = one + (num1 < 3 && num2 < 7 ? two : 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM