Contact FutureLearn for Support
Skip main navigation
We use cookies to give you a better experience, if that’s ok you can close this message and carry on browsing. For more info read our cookies policy.
We use cookies to give you a better experience. Carry on browsing if you're happy with this, or read our cookies policy for more information.

Operator precedence

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.

Operators Precedence
unary !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >=
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

This means if we have, for example, the two operators * and + in a single statement, the * operator will be evaluated first.

For example:

	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.

Share this article:

This article is from the free online course:

Begin Programming: Build Your First Mobile Game

University of Reading