Java Reference
In-Depth Information
You could rewrite this if-else statement example to use the conditional operator, as
follows:
System.out.println((n&1) == 1 ? "odd" : "even");
.
However, you cannot do so with the following example:
if ((n&1) == 1)
odd();
else
even();
This example assumes the existence of
odd()
and
even()
methods that don't re-
turnanything.Becausetheconditionaloperatorrequiresthateachofitssecondandthird
operandsevaluatestoavalue,thecompilerreportsanerrorwhenattemptingtocompile
(n&1) == 1 ? odd() : even()
.
You can chain multiple if-else statements together, resulting in the following syntax:
if (
Boolean expression1
)
statement1
else
if (
Boolean expression2
)
statement2
else
…
else
statementN
If
Boolean expression1
evaluatestotrue,
statement1
executes.Otherwise,
if
Boolean expression2
evaluatestotrue,
statement2
executes.Thispattern
continues until one of these expressions evaluates to true and its corresponding state-
mentexecutes,orthefinal
else
isreachedand
statementN
(thedefaultstatement)
executes.
The following example demonstrates this chaining:
if (testMark >= 90)
{
gradeLetter = 'A';
System.out.println("You aced the test.");
}
else
if (testMark >= 80)
{