InterviewSolution
| 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: Associativity example: 12 * 2 / 4Operators * 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)
|
||||||||||||||||||||||||||||||||||||||||||||||