Java Operator PrecedenceIn this section, we will learn the operator precedence in Java along with examples. What is operator precedence?The operator precedence represents how two expressions are bind together. In an expression, it determines the grouping of operators with operands and decides how an expression will evaluate. While solving an expression two things must be kept in mind the first is a precedence and the second is associativity. PrecedencePrecedence is the priority for grouping different types of operators with their operands. It is meaningful only if an expression has more than one operator with higher or lower precedence. The operators having higher precedence are evaluated first. If we want to evaluate lower precedence operators first, we must group operands by using parentheses and then evaluate. AssociativityWe must follow associativity if an expression has more than two operators of the same precedence. In such a case, an expression can be solved either left-to-right or right-to-left, accordingly. Java Operator Precedence TableThe following table describes the precedence and associativity of operators used in Java.
Note: Larger the number higher the precedence.Java Operator Precedence ExampleLet's understand the operator precedence through an example. Consider the following expression and guess the answer. You might be thinking that the answer would be 18 but not so. Because the multiplication (*) operator has higher precedence than the addition (+) operator. Hence, the expression first evaluates 5*3 and then evaluates the remaining expression i.e. 1+15. Therefore, the answer will be 16. Let's see another example. Consider the following expression. In the above expression, * and / operations are performed before + because of precedence. y is multiplied by z before it is divided by k because of associativity. Next TopicPrivate Constructor in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India