String concatenation does not work properly in Java when concatenating 2 results of ternary operators

拈花ヽ惹草 提交于 2019-12-03 21:53:24

问题


Dear Java guru 's!

Can you, please, explain me, why String concatenation does not work properly in Java when concatenating 2 results of ternary operators?

Example:

String str = null;
String x = str != null ? "A" : "B" + str == null ? "C" : "D";
System.out.println(x);

Output is "D", but I expected "BC".

I am suspecting that it works like so because of operators priorities, but I am not sure, about how we exactly we get "D" for case above. What calculation algorithm takes place for this case?


回答1:


It's interpreted as following code:

String x = str != null ? "A" : ("B" + str == null ? "C" : "D");

"B" + str is not null so it will be evaluated as "D"

With help of OSborn's answer you can do what you expect with this code:

String x = (str != null ? "A" : "B") + (str == null ? "C" : "D");

and since you are just comparing str with null and both conditional statements are almost the same, it can be shortened like this:

 String x = (str != null ? "AD" : "BC");



回答2:


The problem is probably the order of operations. You can make it explicit by writing:

String x = (str != null ? "A" : "B") + (str == null ? "C" : "D");



回答3:


"B" + str == null ? "C", String concatenation evaliated first before the conditional expression evaluated




回答4:


I think you intended

String x = (str != null ? "A" : "B") + (str == null ? "C" : "D");


来源:https://stackoverflow.com/questions/22117029/string-concatenation-does-not-work-properly-in-java-when-concatenating-2-results

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