Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 476
daniilyar Avatar asked Dec 15 '22 01:12

daniilyar


2 Answers

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");
like image 135
Mohammad Jafar Mashhadi Avatar answered Mar 01 '23 22:03

Mohammad Jafar Mashhadi


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");
like image 40
OSborn Avatar answered Mar 01 '23 23:03

OSborn