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

前端 未结 4 1427
无人及你
无人及你 2021-01-03 05:05

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?

相关标签:
4条回答
  • 2021-01-03 05:35

    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");
    
    0 讨论(0)
  • 2021-01-03 05:36

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

    0 讨论(0)
  • 2021-01-03 05:41

    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");
    
    0 讨论(0)
  • 2021-01-03 05:43

    I think you intended

    String x = (str != null ? "A" : "B") + (str == null ? "C" : "D");
    
    0 讨论(0)
提交回复
热议问题