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.
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
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
Operator Precendence in Programming
Computer work in the same PEMDAS pattern for those priorities, but add several levels.
|left to right||access array elements|
access object member
|n/a||unary post increment
unary post decrement
|right to left||unary pre increment
unary pre decrement
|right to left||cast
|12||* / %||left to right||multiplication / division|
|left to right||addition / subtraction
|10||<< >> >>>||left to right||shift|
|9||< <= > >=
|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.