Java ternary operator precedence ? Different outputs given

前端 未结 3 1089
轮回少年
轮回少年 2021-01-20 11:48

I have the below code producing this output (no space after -1) ==> \"1 3 -14 -15 -1\"

int [] arr = {1, 3, Integer.MAX_VALUE, 4         


        
相关标签:
3条回答
  • 2021-01-20 11:53

    Here

    (dist == Integer.MAX_VALUE) ? -1 : dist + " "
    

    The space will be added only if the condition is false. You should use parantheses to add " " at all times like below.

    ((dist == Integer.MAX_VALUE) ? -1 : dist) + " "
    

    The ternary operator has only operator precedence over the assignment operators. (See below)


    Oracle Site about Operator Precedence

    The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence.

    0 讨论(0)
  • 2021-01-20 12:08

    It's just a simple problem with your parentheses. Try this:

    int [] arr = {1, 3, Integer.MAX_VALUE, 4, Integer.MAX_VALUE, 5, Integer.MAX_VALUE};
    
        for (int dist : arr) {
            System.out.print(((dist == Integer.MAX_VALUE) ? -1 : dist) + " ");
        }
    
    0 讨论(0)
  • 2021-01-20 12:15

    You missed to put the operation within parenthesis, so it is behaving weirdly, use below code,

    try{
            throw new ArithmeticException("Exception Testing...");
        }catch(Exception e){
            String msg = "First Statement : " + (e.getCause() != null ? e.getMessage() : null);
    
            System.out.println(msg);
         }
    

    In case you need any other help or explanation on this . Please let me know.

    0 讨论(0)
提交回复
热议问题