Java Reference
In-Depth Information
Table 2.5
Java Operator Precedence
Description
Operators
unary operators
++, --, +, -
multiplicative operators
*, /, %
additive operators
+, -
assignment operators
=, +=, -=, *=, /=, %=
( -- x ) and postdecrement ( x -- ) operators. The pre- versus post- distinction doesn't
matter when you include them as statements by themselves, as in these two exam-
ples. The difference comes up only when you embed these statements inside more
complex expressions, which we don't recommend.
Now that we've seen a number of new operators, it is worth revisiting the issue of
precedence. Table 2.5 shows an updated version of the Java operator precedence table
that includes the assignment operators and the increment and decrement operators.
Notice that the increment and decrement operators are grouped with the unary opera-
tors and have the highest precedence.
Did You Know?
++ and --
The ++ and -- operators were first introduced in the C programming language.
Java has them because the designers of the language decided to use the syntax of
C as the basis for Java syntax. Many languages have made the same choice,
including C++ and C#. There is almost a sense of pride among C programmers
that these operators allow you to write extremely concise code, but many other
people feel that they can make code unnecessarily complex. In this topic we
always use these operators as separate statements so that it is obvious what is
going on, but in the interest of completeness we will look at the other option here.
The pre- and post- variations both have the same overall effect—the two incre-
ment operators increment a variable and the two decrement operators decrement a
variable—but they differ in terms of what they evaluate to. When you increment or
decrement, there are really two values involved: the original value that the variable
had before the increment or decrement operation, and the final value that the vari-
able has after the increment or decrement operation. The post- versions evaluate to
the original (older) value and the pre- versions evaluate to the final (later) value.
Consider, for example, the following code fragment:
int x = 10;
int y = 20;
int z = ++x * y--;
Continued on next page
 
Search WWH ::




Custom Search