问题
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