## Precedences of operators

You know that multiplication * takes precedence over addition +, e.g. the expression 5 + 4 * 3 is evaluated as if it were parenthesized like this: 5 + (4 * 3).

Mathematics has conventions for precedences of operators in order to reduce the number of parentheses required in writing complex expressions. Some of these conventions are standard throughout the world —like * over +. Others are not.

Below is a table of precedences for Java operators. Refer to this table, or the one on p. 227 of Gries/Gries, if you forget the precedences.

#### Table of operator precedences

ORDER | OPERATORS | EXAMPLES |
---|---|---|

Highest | Unary ops: | + – ++ –– ! |

Binary arithmetic ops. | * / % | |

Binary arithmetic ops. | + – | |

Arithmetic relations: | < > <= >= | |

Equality relations: | == != | |

Logical and: | && | |

Lowest | Logical or: | || |

For example, the expression

(n != 0) && (10/n > 2)

can be easily rewritten as

n != 0 && 10/n > 2

because relational operators have precedence over &&.

#### Keep redundant parentheses to a minimum (but don't sacrifice clarity)

Your goal in writing expressions should be to make them a clear and simple-looking as possible, and this can often be done by eliminating redundant expressions —but you can help the reader by putting more space around operators with less precedence. For example, the two assignment statements shown below have the same meaning, but the second is easier to read.

b= ((x<=y)||(x<=z));

b= x <= y || y <= z;

Keep redundant parentheses to a minimum. For example, they are not needed in a return statement within a function body (you will learn about the return statement later): the following two statements are equivalent, but the second is easier to read.

return (x >= -10 && x <= 10);

return x >= -10 && x <= 10;

#### About AND and OR

Java gives && precedence over ||, so that b || c && d is equivalent to b || (c && d). This convention is non-standard, and controversial for some. Therefore, when writing sequences of &&s and ||s, we suggest always putting in parentheses to make the meaning clear.

This is a case where the suggestion to eliminate redundant parentheses is overruled in favor of removing confusion and providing clarity.