1.

What do you understand about order of precedence and associativity in Java, and how do you use them?

Answer»

Order of precedence:

The operators are arranged in order of precedence. When a number of operators are employed in an expression, the priorities of the operators determine how the expression is evaluated. In an expression CONTAINING multiple operators with various PRECEDENCES, operator precedence decides which one is executed first.

Order of precedence example:

(4 > 2 + 8 && 3)

The following expression is the same as:

((4 > (2 + 8)) && 3)

The expression (2 + 8) will be executed first, yielding a value of 10.

After the first HALF of the equation (4 > 10) executes, the output is 0 (false).

Finally, (0 && 3) runs and returns 0. (false).

Associativity:
When two operators with the same precedence EXIST in an expression, associativity is employed. Left to right or right to left associativity is possible. To determine whether an expression is evaluated from left to right or right to left, associativity is used.

Associativity example:

 12 * 2 / 4

Operators * and / have the same precedence in this case. "*" and "/" are both left to right associative, which means that the expression on the left is executed first and then moves to the right.

As a result, the preceding expression is identical to:

((12 * 2) / 4) i.e., (12 * 2) executes first and the result will be 24 (true) then, (24 / 4) executes and the final output will be 6 (true)
CATEGORYOPERATORASSOCIATIVITY
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


Discussion

No Comment Found