I had to create an output depending on an boolean state like
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", " + smily == null ? ":)" : ":("); //$NON-NLS-1$
System.out.println(buff.toString());
The problem is the String creation statement
", " + smily == null ? ":)" : ":("
I tested it in 2 different eclipse environments (and may be also 2 diofferent java version, this i did not checked) and the result was different.
Result 1:
🙁
Result 2:
false:(
Of course, if i added brackets it is working
buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$
Expected Result:
, 🙂
Can please somebody explain to me, why java interprets the statement that way?
Thanks
If you check the operator precedence (see this tutorial), then you will notice that addition (
+) comes before equality (==). In other words, Java will first evaluate", " + smily=>", null"before evaluating equality, therefor", " + smily == nullevaluates to false, and so the ternary operator evaluates to":(".BTW: You could have avoided this by not concatenating strings before adding them to the
StringBuffer(the whole point of a StringBuffer is to make concatenation cheaper):