Java ternary operator precedence ? Different outputs given

落爺英雄遲暮 提交于 2019-12-04 04:02:31

问题


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, Integer.MAX_VALUE, 5, Integer.MAX_VALUE};
for (int dist : arr) {
    System.out.print((dist == Integer.MAX_VALUE) ? -1 : dist + " ");
}

But if I evaluate the ternary expression separately (as shown below), it gives a different output (what I expected) ==> "1 3 -1 4 -1 5 -1"

int [] arr = {1, 3, Integer.MAX_VALUE, 4, Integer.MAX_VALUE, 5, Integer.MAX_VALUE}; 
for (int dist : arr) {
    int finalDist = (dist == Integer.MAX_VALUE) ? -1 : dist;
    System.out.print(finalDist + " ");          
}

What is going wrong with the first code snippet?


回答1:


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.




回答2:


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) + " ");
    }



回答3:


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.



来源:https://stackoverflow.com/questions/33857571/java-ternary-operator-precedence-different-outputs-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!