Operators Precedence in Java

In Java, operators have a specific precedence, which determines the order in which they are evaluated in expressions. When an expression contains multiple operators, Java follows these rules to determine the order of evaluation:

  1. Parentheses: Expressions inside parentheses are evaluated first. If there are nested parentheses, the innermost expressions are evaluated first.
  2. Postfix Operators: Postfix operators, such as ++ (increment) and -- (decrement), are applied after the current value is used in the expression.
  3. Multiplicative Operators: Multiplicative operators, including * (multiplication), / (division), and % (modulo), have the next highest precedence.
  4. Additive Operators: Additive operators, which are + (addition) and - (subtraction), have lower precedence than multiplicative operators.
  5. Relational Operators: Relational operators, including <, <=, >, and >=, are used for comparisons and have lower precedence than shift operators.
  6. Equality Operators: Equality operators, which are == (equal to) and != (not equal to), have lower precedence than relational operators.
  7. Logical AND Operator: The && (logical AND) operator has lower precedence than the bitwise OR operator.
  8. Logical OR Operator: The || (logical OR) operator has the lowest precedence among the binary operators.
  9. Assignment Operators: Assignment operators, such as =, +=, -=, *=, /=, and so on, have the lowest precedence among all operators.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

It's important to note that when operators of the same precedence level appear in an expression, they are evaluated from left to right. This is known as left-associativity.

You can use parentheses to explicitly specify the order of evaluation when needed, regardless of operator precedence. This can make your code more readable and ensure that expressions are evaluated as intended.


Comments

Popular posts from this blog

Lecture 2 - How to Take Input From User in Java

Programming Conventions in Java

Why Java is Called Java?