Do you remember PEMDAS from school?

If you don’t, it’s the order of operations in math problems. Stuff in parenthesis happens first, followed by exponents, multiplication & division, and addition & subtraction. It’s why `3 + 7 * 2`

is 17. 7 is multiplied by 2 first before the 3 is added.

How does this apply to computers? Read on…

## A few terms…

Let’s start with some vocabulary.

### Precedence Order

The first column below is the precedence of the operators. The higher the number, the higher the operator precedence. All else being equal, something on line 12 will happen before something on line 3.

For example, multiplication is on line 12 and addition is on line 11. That’s why `3 + 7 * 2 = 17`

, not `20`

.

### Associativity

If you’ve got multiple operations that are the same precedence order you then fall to associativity to see what happens next.

We’ll got with some simple math. `1 + 2 - 3`

. Addition and subtraction have the same precedence, so we’ll look at associativity, which is left to right in this case. So we add `1+2`

and the add `3`

to equal `6`

.

## Operator Precendence in Programming

Computer work in the same PEMDAS pattern for those priorities, but add several levels.

Level | Operators | Associativity | Description |
---|---|---|---|

16 | [] . () |
left to right | access array elements access object member parentheses |

15 | ++ — |
n/a | unary post increment unary post decrement |

14 | ++ — + – ! ~ |
right to left | unary pre increment unary pre decrement unary plus unary minus logical not unary bitwise |

13 | () new |
right to left | cast object creation |

12 | * / % | left to right | multiplication / division |

11 | + – + |
left to right | addition / subtraction concatenation |

10 | << >> >>> | left to right | shift |

9 | < <= > >= instanceof |
n/a | realtional comparisons |

8 | == != |
left to right | equality |

7 | & | left to right | bitwise AND |

6 | ^ | left to right | bitwise XOR |

5 | | | left to right | bitwise OR |

4 | && | left to right | bitwise AND |

3 | || | left to right | bitwise OR |

2 | ?: | right to left | ternary |

1 | = += -= *= /= %= &= ^= |= <<= >=>= >>>= |
right to left | assignment |

Interesting side note for you. This order of operator precedence is not specified in the language specification for Java, so you might see it a little different in different places. But it should be pretty close, and not different in ways that should change results.

Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?