String concatenation does not work in Java when concatenating two results of a ternary operator

Dear Java master!

Please explain why concatenation does not work properly in Java when connecting two results of ternary operators?

Example:

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

The output is "d", but I expect "BC"

Because of the priority of the operator, I doubt it is, but I'm not sure about how we get "d" in the above case What calculation algorithm will be used in this case?

Solution

It is interpreted as the following code:

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

"B" STR is not empty, so it will be evaluated as "d"

With the help of Osborn's answer, you can use this code to perform the desired operations:

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

And because you only compare STR with null and the two conditional statements are almost the same, it can be shortened to:

String x = (str != null ? "AD" : "BC");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>