Java Reference
In-Depth Information
To understand how the expression above is evaluated, take a look back at the precedence table for operators
that we introduced in the last chapter. You will see that the comparison operators are all of lower precedence
than the arithmetic operators, so arithmetic operations will always be completed before any comparisons are
made, unless of course there are parentheses saying otherwise. The expression,
x - y == a + b
will produce the result true if x-y is equal to a+b , since these arithmetic sub-expressions will be
evaluated first, and the values that result will be the operands for the == operator. Of course, it is
helpful to put the parentheses in, even though they are not strictly necessary. It leaves no doubt as to
what is happening if you write:
(x - y) == (a + b)
Note that if the left and right operands of a relational operator are of differing types, values will be
promoted in the same way as we saw in the last chapter for mixed arithmetic expressions. So if
aDouble is of type double , and number is of type int , in the following expression:
aDouble < number + 1
the value produced by number + 1 will be calculated as type int , and this value will be promoted to
type double before comparing it with the value of aDouble .
The if Statement
The first statement we will look at that can make use of the result of a comparison is the if statement.
The if statement, in its simplest configuration, is of the form:
if(expression)
statement;
where expression can be any expression that produces a value true or false . You can see a
graphical representation of this logic in the following diagram:
No
expression is
?
true
if (expression)
statement;
next_statement;
yes
execute
statement
execute
next_statement
Search WWH ::




Custom Search