Java Reference
In-Depth Information
condition ? value 1 : value 2
The value of that expression is either value 1 if the condition is true or value 2 if it is
false. For example, we can compute the absolute value as
y = x >= 0 ? x : -x;
which is a convenient shorthand for
if (x >= 0)
y = x;
else
y = -x;
The selection operator is similar to the if/else statement, but it works on a
different syntactical level. The selection operator combines values and yields
another value. The if/else statement combines statements and yields another
statement.
For example, it would be an error to write
y = if (x < 0) x; else -x; // Error
The if/else construct is a statement, not a value, and you cannot assign it to a
variable.
We don't use the selection operator in this topic, but it is a convenient and
legitimate construct that you will find in many Java programs.
187
188
5.2 Comparing Values
5.2.1 Relational Operators
A relational operator tests the relationship between two values. An example is the
<= operator that we used in the test
Relational operators compare values. The == operator tests for equality.
if (amount <= balance)
Search WWH ::




Custom Search