Java Reference
In-Depth Information
Table 4.2
Java Operator Precedence
Description
Operators
unary operators
++, --, +, -
multiplicative operators
*, /, %
additive operators
+, -
relational operators
<, >, <=, >=
equality operators
==, !=
assignment operators
=, +=, -=, *=, /=, %=
Because we use the relational operators as a new way of forming expressions,
we must reconsider precedence. Table 4.2 is an updated version of Table 2.5
that includes these new operators. You will see that, technically, the equality com-
parisons have a slightly different level of precedence than the other relational
operators, but both sets of operators have lower precedence than the arithmetic
operators.
Let's look at an example. The following expression is made up of the constants 3 ,
2 , and 9 and contains addition, multiplication, and equality operations:
3 + 2 * 2 == 9
Which of the operations is performed first? Because the relational operators have a
lower level of precedence than the arithmetic operators, the multiplication is per-
formed first, then the addition, then the equality test. In other words, Java will perform
all of the “math” operations first before it tests any relationships. This precedence
scheme frees you from the need to place parentheses around the left and right sides
of a test that uses a relational operator. When you follow Java's precedence rules, the
sample expression is evaluated as follows:
3 + 2 * 2 == 9
3 +
4
== 9
7
== 9
false
You can put arbitrary expressions on either side of the relational operator,
as long as the types are compatible. Here is a test with complex expressions on
either side:
(2 - 3 * 8) / (435 % (7 * 2)) <= 3.8 - 4.5 / (2.2 * 3.8)
 
Search WWH ::




Custom Search