It seems you are confused about what “higher precedence” means. Let’s explain with a simple example:
The operator *
has higher precedence than the operator '+'. This means that the expression a*b+c
is evaluated like (a*b)+c
. The same applies to the &&
operator and the ternary operator:
&&
has higher precedence than the operator ? :
. This means that the expression a&&b?c:d
is evaluated as (a&&b)?c:d
.
Hence the operator precedence works as documented in your example. It does exactly what you requested:
if (a.getItem() != null && a.getItem().getOtherItem() != null?
true:a.getItem().getOtherItem().getSomevalue())
If a.getItem()
is not null and a.getItem().getOtherItem()
is not null evaluate to true, otherwise to a.getItem().getOtherItem().getSomevalue()
. So when either of the values is null, the code will attempt to evaluate the third term which will yield to a NullPointerException
.
It’s not clear what you actually want to achieve. In your second example you say:
if (a.getItem() != null && (a.getItem().getOtherItem() != null?
true: a.getItem().getOtherItem().getSomevalue()))
so you want to interpret the case when a.getItem()
is null
as false
but in the braced term you request to interpret the case when a.getItem().getOtherItem()
is not null
as true
while the case that a.getItem().getOtherItem()
is null
should cause getSomevalue()
to be called on the reference that you just have proven to be null
.
What you most likely want to do is to evaluate a.getItem().getOtherItem().getSomevalue()
if the all values are not null:
if (a.getItem() != null && a.getItem().getOtherItem() != null?
a.getItem().getOtherItem().getSomevalue(): false)
Note that you can express the same without the ternary operator at all. The equivalent statement would be:
if (a.getItem() != null && a.getItem().getOtherItem() != null
&& a.getItem().getOtherItem().getSomevalue())
In the case the fall-back value ought to be true
like in
if (a.getItem() != null && a.getItem().getOtherItem() != null?
a.getItem().getOtherItem().getSomevalue(): true)
the same can be expressed as
if (a.getItem() == null || a.getItem().getOtherItem() == null
|| a.getItem().getOtherItem().getSomevalue())
Whenever you see true
or false
in a compound boolean
expression you can be sure that there is something wrong.