When there is more than one operator in a statement, operators with higher precedence are evaluated before operators with lower precedence.
Some operators have same level of precedence in which case a rule should govern which is evaluated first.
The following table (adapted from the Java operator documentation) shows the order of operator precedence. Operator precedence decreases from top to bottom.
|multiplicative||* / %|
|shift||<< >> >>>|
|relational||< > <= >=|
|bitwise exclusive OR||^|
|bitwise inclusive OR||||
|assignment||= += -= *= /= %= &= ^= |= <<= >>= >>>=|
This means if we have, for example, the two operators * and + in a single statement, the * operator will be evaluated first.
int mBallX = 100; int mBallY = 5; int resultA = mBallX + 5 * mBallY;
Because the * operator has higher precedence than the + operator, this part of the statement is executed first. This means that the value of
resultA is 125 (calculated as
mBallX + (5 * mBallY)) rather than 525 as it would be if the + operator had precedence (which would be calculated as
(mBallX + 5) * mBallY).
As you can see, it’s important to understand operator precedence so that we can ensure we get the results that we expect in our programs.
Notes: If we wanted to
resultA to equal 525, we would have to restructure the statement to take into account operator precedence. By using parenthesis (brackets) you can enforce precedence in a similar way that you can in mathematical statements.
© University of Reading