In both C#/Java the operator precedence of is
respectively instanceof
leads to some ugly necessary parenthesis. For example instead of writing if (!bar instanceof Foo)
you have to write if (!(bar instanceof Foo))
.
So why did the language teams decide that !
has a higher operator precedence than is/instanceof? Admittedly in C# you can overwrite operator!
which would lead to a different result in some situations, but those situations seems exceedingly rare (and non-intuitive in any case), while the case of checking if something is not a type or subtype of something is much more likely.
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.
Explanation: Operator ++ has the highest precedence than / , * and +.
The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .
In Java, instanceof
is one of the relational operators and has the same precedence as the other ones:
RelationalExpression:
ShiftExpression
RelationalExpression < ShiftExpression
RelationalExpression > ShiftExpression
RelationalExpression <= ShiftExpression
RelationalExpression >= ShiftExpression
RelationalExpression instanceof ReferenceType
From that perspective it makes sense that those two lines should follow the same structure:
if (!(a instanceof b))
if (!(a < b))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With