Read this chapter, which covers variables and arithmetic operations and order precedence in Java.
21. Arithmetic Operators
Answer:
12, since the expression means: 12 - 2 + 2
Arithmetic Operators
An arithmetic operator is a symbol that asks for two numbers to be combined by 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 the precedence of some Java operators.
Some operators have equal precedence. For example, addition +
and subtraction -
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 both operands (the numbers) are integers, these operators do integer arithmetic. If one operand or both operands are 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
is2
(not2.5
)
5/10
is0
(not0.5
).
However,
5.0/2.0
is2.5
5/10
is0.5
.
Operator | Meaning | precedence |
---|---|---|
- | unary minus | highest |
+ | unary plus | highest |
* | multiplication | middle |
/ | division | middle |
% | remainder | middle |
+ | addition | low |
- | subtraction | low |
Question 22:
What is the value of the following expressions? In each expression, do the
highest precedence operator first.