4

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?

daniilyar
  • 2,602
  • 3
  • 22
  • 25
  • 2
    The precedence isn't what you expected. When in doubt, add parentheses. – keshlam Mar 01 '14 at 16:33
  • 3
    I feel like this is a case where ternaries reduce readability. – David DeMar Mar 01 '14 at 16:33
  • Yes, I agree. I am currently mentoring an appropriate [issue in Checkstyle sandbox](https://github.com/sevntu-checkstyle/sevntu.checkstyle/issues/167). In this issue we want to let others prevent such unreadable ternary-based expressions in their code by using Checkstyle – daniilyar Mar 01 '14 at 16:47
  • In fact, code like this is what gives ternaries a bad name and makes people come up with too-broad rules like "never use the ternary operator." – yshavit Mar 01 '14 at 17:18
  • Why never? I think it is better to let people decide what count of ternaries could be allowed per one expression – daniilyar Mar 01 '14 at 18:31

4 Answers4

8

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");
Mohammad Jafar Mashhadi
  • 4,102
  • 3
  • 29
  • 49
  • Now I understand, thank you very much! Linked this answer with [related issue in Checkstyle sandbox](https://github.com/sevntu-checkstyle/sevntu.checkstyle/issues/167) as best explanation – daniilyar Mar 01 '14 at 16:42
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");
OSborn
  • 895
  • 4
  • 10
1

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

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
1

I think you intended

String x = (str != null ? "A" : "B") + (str == null ? "C" : "D");
keshlam
  • 7,931
  • 2
  • 19
  • 33