Search Logic Blocks

Wednesday, January 22, 2020

Java: Precedence of operators

We have learnt about all the operators - Arithmetic OperatorsAssignment OperatorsRelational OperatorsLogical OperatorsBitwise Operators and Conditional Operator in my earlier posts. But when there are more than one operator in one expression, there is some precedence. Whoever has studied mathematics, I think they know BODMAS (Brackets first,  Orders 'Powers or Square Roots', Division and Multiplication, Addition and Subtraction) rule to solve the equations. Same thing applies here. Here is the list of precedence of operators in Java -

CategoryOperatorAssociativity
Postfixexpression++ expression--Left to right
Unary++expression –-expression +expression –expression ~ !Right to left
Multiplicative* / %Left to right
Additive+ -Left to right
Shift<< >> >>>Left to right
Relational< > <= >= instanceofLeft to right
Equality== !=Left to right
Bitwise AND&Left to right
Bitwise XOR^Left to right
Bitwise OR|Left to right
Logical AND&&Left to right
Logical OR||Left to right
Conditional?:Right to left
Assignment= += -= *= /= %= ^= |= <<= >>= >>>=Right to left
Here is an example below -

8 - 2 * 3 = 6 * 3 = 18 X Wrong

8 - 2 * 3 = 8 - 6 = 2   √ Right

Here is another example -

false && true == false => false == false => true    X Wrong

false && true == false => false && false => false  √ Right

NOTE: instanceof operator is related to classes and objects. We will talk about it later.

No comments: