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?
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");