Conditional Operator

Uses the result of the first expression to select which of the next two expressions to evaluate and return.

The conditional operator evaluates the first expression (a boolean) and uses the result to select which of the second and third expressions to evaluate and return. If the first expression evaluates to true, the second is selected and returned. If the first evaluates to false, the third is evaluated and returned.

isRaining() ? "It's raining!" : "Clear skies!";

If it's raining (isRaining() returns true), this expression evaluates to "It's raining!". Otherwise this expression evaluates to "Clear skies!".

Syntax

Conditional Operators can be expressed through:

1 bool-expr ? expr1 : expr2

where...

bool-expr is an expression whose type is boolean (or its wrapper type, Boolean).
expr1 is any non-void expression, including assignment expressions.
expr2 is a any non-void expression except for assignment expressions.
A non-void expression is an expression whose type is not void. In other words, any expression except for an invocation of a void method.

Syntax Elements

1 A conditional expression.

Usage

Ternary expressions are used to conditionally select one of two expressions based on the result of a boolean expression. They are, in some sense, the expression form of an if statement. The following:

if (condition)
	return "value1";
else
	return "value2";

is equivalent to:

return condition ? "value1" : "value2";

because the expression condition ? "value1" : "value2" evaluates to "value1" if condition is true and "value2" if condition is false.

Examples

Notes