Re: operator precedance
sakcee@gmail.com wrote:
I looked up that precedance should be + --> == --> ?: but still I am
confused, I was wondering
if anyone can tell me how this will be evaluated.
volume == null ? "" : volume + file == null ? "" : file + version ==
null ? "" : version;
It doesn't help that it is all one long line. You seem to have got the
precedence, but not the associativity.
a-b-c means (a-b)-c not a-(b-c)
a=b=c means a=(b=c) not (a=b)=c
a?b:c?d:e means a?b:(c?d:e) not (a?b:c)?d:e
That is to say, the ?: operator has right to left associativity.
Going back to the original example, we can write it more clearly:
String display =
volume==null ? "" :
volume+file==null ? "" :
file+version==null ? "" :
version;
Of course an expression a+b for any a, b will never result in null. So,
presumably what was meant was:
String display =
(volume ==null ? "" : volume ) +
(file ==null ? "" : file ) +
(version==null ? "" : version);
Or more explicitly:
StringBuilder display = new StringBuilder();
if (volume != null) {
display.append(volume);
}
if (file != null) {
display.append(file);
}
if (version != null) {
display.append(version);
}
My approach to the ternary operator:
o Layout the code out sensibly.
o Line things up, where it makes sense to do so.
o The condition is often of the form a==b. Don't use parentheses for
that, but do for anything complicated.
o Generally don't put spaces in the condition subexpression.
o For most expressions there is no issues of precedence between the ?
and :, so don't bother with parentheses there.
o If the last expression is not a simple variable/literal/method add
parentheses.
o Do not use ?: where it does not match the problem.
o If things get too complicated, revert to if-else statements.
[Disclaimer: I have not compiled or tested any of this code.]
Tom Hawtin