Java Reference
In-Depth Information
Note the use of “||” instead of “|”. Because of this usage, if score > 75000 is true,
extraLife is set to true , and the second expression is never evaluated.
The XOR combination has one logical operator, “^”. This results in a true value only if
both Boolean expressions it combines have opposite values. If both are true or both are
false, the “^” operator produces a false value.
The NOT combination uses the “!” logical operator followed by a single expression. It
reverses the value of a Boolean expression the same way that a minus symbol reverses
the positive or negative sign on a number.
2
For example, if age < 30 returns a true value, !(age < 30) returns a false value.
The logical operators can seem completely illogical when encountered for the first time.
You get plenty of chances to work with them for the rest of this week, especially on Day
5, “Creating Classes and Methods.”
Operator Precedence
When more than one operator is used in an expression, Java has an established prece-
dence hierarchy to determine the order in which operators are evaluated. In many cases,
this precedence determines the overall value of the expression.
For example, consider the following expression:
y = 6 + 4 / 2;
The y variable receives the value 5 or the value 8 , depending on which arithmetic opera-
tion is handled first. If the 6 + 4 expression comes first, y has the value of 5 . Otherwise,
y equals 8 .
In general, the order of evaluation from first to last is the following:
Increment and decrement operations
n
Arithmetic operations
n
Comparisons
n
Logical operations
n
Assignment expressions
n
If two operations have the same precedence, the one on the left in the actual expression
is handled before the one on the right. Table 2.6 shows the specific precedence of the
various operators in Java. Operators farther up the table are evaluated first.
Search WWH ::




Custom Search