Java Reference
In-Depth Information
Here, the value assigned to
var
depends upon the outcome of the condition controlling the
if
.
The
?
is called a
ternary operator
because it requires three operands. It takes the general
form
Exp1 ? Exp2 : Exp3;
where
Exp1
is a
boolean
expression, and
Exp2
and
Exp3
are expressions of any type other
than
void
. The type of
Exp2
and
Exp3
must be the same (or compatible), though. Notice
the use and placement of the colon.
The value of a
?
expression is determined like this:
Exp1
is evaluated. If it is true, then
Exp2
is evaluated and becomes the value of the entire
?
expression. If
Exp1
is false, then
Exp3
is evaluated and its value becomes the value of the expression. Consider this example,
which assigns
absval
the absolute value of
val
:
Here,
absval
will be assigned the value of
val
if
val
is zero or greater. If
val
is negative,
then
absval
will be assigned the negative of that value (which yields a positive value). The
same code written using the
if-else
structure would look like this:
Here is another example of the
?
operator. This program divides two numbers, but will
not allow a division by zero.