Highest precedence in Java
When we talk about precedence in Java, the operator comes first in mind. There are certain rules defined in Java to specify the order in which the operators in an expression are evaluated. Operator precedence is a concept of determining the group of terms in an expression. The operator precedence is responsible for evaluating the expressions. In Java, parentheses() and Array subscript have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.
Below is a table defined in which the lowest precedence operator show at the top of it.
When two operators share a single operand, the operator having the highest precedence goes first. For example, x + y * z is treated as x + (y * z), whereas x * y + z is treated as (x * y) + z because * operator has highest precedence in comparison of + operator.
Associative is a concept related to the operators applied when two operators with the same precedence come in an expression. The associativity concept is very helpful to goes from that situation. Suppose we have an expression a + b - c (+ and - operators have the same priority), and this expression will be treated as (a + (b - c)) because these operators are right to left-associative. On the other hand, a+++--b+c++ will be treated as ((a++)+((--b)+(c++))) because the unary post-increment and decrement operators are right to left-associative.
An example is defined below to understand how an expression is evaluated using precedence order and associativity?
Expression: x = 4 / 2 + 8 * 4 - ( 5+ 2 ) % 3
1) In the above expression, the highest precedence operator is (). So, the parenthesis goes first and calculates first.
x = 4 / 2 + 8 * 4 - 7 % 3
2) Now, /, * and % operators have the same precedence and highest from the + and - Here, we use the associativity concept to solve them. The associative of these operators are from left to right. So, / operator goes first and then * and % simultaneously.
x = 2 + 8 * 4 - 7 % 3
x = 2 + 32 - 7 % 3
x = 2 + 32 - 1
3) Now, + and - operators both also have the same precedence, and the associativity of these operators lest to the right. So, + operator will go first, and then - will go.
x = 34 - 1
x = 33