What is the value of: 12 - 4/2 + 2
12, since the expression means: 12 - 2 + 2
An arithmetic operator is a symbol that asks for doing some arithmetic. As the previous question illustrates, if several operators are used in an expression, the operations are done in a specific order. Operators of higher precedence are done first. The table shows just a few of the many operators in Java.
Operator | Meaning | precedence |
---|---|---|
- | unary minus | highest |
+ | unary plus | highest |
* | multiplication | middle |
/ | division | middle |
% | remainder | middle |
+ | addition | low |
- | subtraction | low |
Some operators have
equal precedence.
For example, plus +
and minus -
have the same precedence.
The unary minus and unary plus operators are used as
part of a negative or a positive number.
For example, -23
means negative twenty-three and
+23
means positive twenty-three.
More on this later.
When the operands (the numbers) are both integers, then these operators do integer arithmetic.
If one or both operand is floating point, then these operators do floating point arithmetic.
This is especially important to remember with division,
because the result of integer division is an integer.
For example, 5/2
is 2
(not 2.5
) and 5/10
is 0
(not 0.5
). More on this later.
What is the value of the following expressions? In each expression, do the highest precedence operator first.
Expression | 16 - 12 / 4 | 2 + 6 / 2 | 8 + 4*2 | 8+4 * 2 | 12/2 - 3 | 6/8 + 2 |
---|---|---|---|---|---|---|
Value? |