ternary operation behaves weirdly [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-10 22:17:00

问题


I have a difficulty in understanding how the ternary operation works in the below code.

public static void main(String[] args) {
        try{
            throw new ArithmeticException("Exception Testing...");
        }catch(Exception e){
            msg = "First Statement : " + e.getCause() != null ? e.getMessage() : null;  //Here e.getCause() is null
            System.out.println(msg);  //  prints "Exception Testing..."
         }
    }

In the first Statement block(Line 4), e.getcause() is null so it should print First Statement: null instead it prints only Exception Testing....

My question is,

1)Why TRUE block got executed in the ternary operation instead of returning null and also,

2)Why First Statement: is not printed with the msg Exception Testing...?

Thanks in advance.


回答1:


Because of operator precedence, + is applied before ?:, so you are checking whether:

"First Statement : " + e.getCause()

is null - it's not.

Add parentheses:

 msg = "First Statement : " + (e.getCause() != null ? e.getMessage() : null);


来源:https://stackoverflow.com/questions/57672066/ternary-operation-behaves-weirdly

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