Java Reference
In-Depth Information
Ternary Operator
? :
Java has a
ternary operator
that allows you to choose between two expressions based
on the value of a
boolean
test. (“Ternary” means “having three sections.”) Think of
it as an abbreviated form of an
if/else
statement, except that an
if/else
chooses
between two blocks of statements, while a ternary expression chooses between two
expressions or values:
<test> ? <expression1> : <expression2>
A ternary expression is most useful when you want to assign a variable one of two
values, or when you want to pass one of two values as a parameter or return value.
For example:
// if d > 10.0, set x to 5; else set x to 2
double d = ...;
int x = d > 10.0 ? 5 : 2;
// e.g. "I have 3 buddies" or "I have 1 buddy"
int pals = ...;
String msg = "I have " + pals + " " + (pals == 1 ? "buddy" :
"buddies");
// Returns the larger of a and b
public static int max(int a, int b) {
return (a > b) ? a : b;
}
Exiting a Loop:
break
and
continue
Java has a statement called
break
that will immediately exit a
while
,
do/while
,or
for
loop. One common usage of
break
is to write a loop that performs its exit test in
the middle of each iteration rather than at the start or end. The common template is to
form what appears to be an infinite loop:
while (true) {
<statement>
;
...
if (
<test>
) {
break;
}
<statement>
;
...
}
Search WWH ::
Custom Search