Java Reference
In-Depth Information
Table 2.4
Java Operator Precedence
Description
Operators
unary operators
+, -
multiplicative operators
*, /, %
additive operators
+, -
The expression now evaluates as follows:
40 - (25 - 9)
40 -
16
24
Another concept in arithmetic is unary plus and minus, which take a single operand,
as opposed to the binary operators we have seen thus far (e.g., *, /, and even binary +
and -), all of which take two operands. For example, we can find the negation of 8 by
asking for -8 . These unary operators have a higher level of precedence than the multi-
plicative operators. Consequently, we can form expressions like the following:
12 * - 8
which evaluates to -96 .
We will see many types of operators in the next few chapters. Table 2.4 is a prece-
dence table that includes the arithmetic operators. As we introduce more operators,
we'll update this table to include them as well. The table is ordered from highest
precedence to lowest precedence and indicates that Java will first group parts of an
expression using the unary operators, then using the multiplicative operators, and
finally using the additive operators.
Before we leave this topic, let's look at a complex expression and see how it is
evaluated step by step. Consider the following expression:
13 * 2 + 239 / 10 % 5 - 2 * 2
It has a total of six operators: two multiplications, one division, one mod, one sub-
traction, and one addition. The multiplication, division, and mod operations will be
performed first, because they have higher precedence, and they will be performed
from left to right because they are all at the same level of precedence:
13 * 2 + 239 / 10 % 5 - 2 * 2
26
+ 239 / 10 % 5 - 2 * 2
26
+ 23 % 5 - 2 * 2
26 +
3
- 2 * 2
26
+
3
-
4
 
Search WWH ::




Custom Search