In this tutorial you will learn about the Java Operator Precedence and Associativity and its application with practical example.
Java Operators Precedence
Operator precedence defines the order in which a given mathematical expression is evaluated. When an expression includes multiple operators then every single part of the given expression is evaluated in a certain order following some rules defined as per operator precedence. The higher precedence is evaluated first and the lowest precedence is evaluated last.
Java Operator Associativity
With the same precedence follow operator associativity defined for their operator group. In Java, operators can either follow left-associative, right-associative, or have no associativity. Operators with left-associative are evaluated from the left to right, operators with right-associative are evaluated from right to the left, and with no associativity, do not follow any predefined order.
Following are the java precedence tables with their respective associativity.
Category | Operator | Associativity |
---|---|---|
Postfix | ++ – – | Left to right |
Unary | + – ! ~ ++ – – | Right to left |
Multiplicative | * / % | Left to right |
Additive | + – | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left 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 |