Operator precedence deciphers the order in which calculations in an expression occur. Looking at the calculation example 3 + 4 * 6, the answer could be calculated by adding 3 and 4, which gives 7, and then multiplying 7 by 6, giving the answer of 42. However, we could also multiply 4 and 6 first, which gives 24, and then add on the 3, giving an answer of 27. The multiplication operator (*) actually has a higher precedence than the addition operator (+). This means that the numeric expression 3 + 4 * 6 would actually give the answer 27 and __not__ 42, executing the multiplication first and then the addition. In order to specify the order in which calculations occur you can simply use parentheses. If we want the addition calculation to be executed before the multiplication, we can enclose the addition calculation in parentheses (e.g., (3 + 4) * 6, which will give us the answer 42). When in doubt, it is recommended that you use parentheses to specify the order of operations. It is often best to use parentheses anyway to make your code more understandable. The following table shows an operator list containing operators with a higher precedence at the top and thoses with a lower precedence at the bottom. The table also shows the *associativity* of grouped operators that are of equal precedence. The associativity deciphers the order of operators of equal precedence. For example, division has a "left" associativity, which you may look upon as being left to right. This means that the expression 24 / 4 / 2 would be the same as (24 / 4) / 2, equaling 3, and would not be the same as the expression 24 / (4 /2), which gives a result of 12. Here is the operator precedence table and the associativity of operators of equal precedence.

Operator Group |
Associativity |
---|---|

(), [], ., postfix++, postfix–– |
Left |

+ unary, – unary, ++prefix, ––prefix, ~, ! |
Right |

new, (cast) |
Left |

*, /, % |
Left |

+, – |
Left |

<<, >>, >>> |
Left |

<, <=, >, >=, instanceof |
Left |

==, != |
Left |

& |
Left |

^ |
Left |

| |
Left |

&& |
Left |

|| |
Left |

?: |
Left |

=, *=, /=, %=, +=, –=, <<=, >>=, >>>=, &=, |=, ^= |
Right |

Thinking back to the two examples that we have looked at so far, we can first see that the multiplication operator is higher up the table than the addition operator, meaning it has a higher precedence. We can also see that the division operator has a left (left to right) associativity, as we previously discussed.

Don't worry about this amass of operators; we will cover them all throughout the tutorial.