CKTIS / Java
Conditional operator ?:
The ?: operator selects one of two values based on a condition. It is an expression with three operands; only the selected branch is evaluated at run time.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
condition ? valueIfTrue : valueIfFalseThe conditional operator ?:, also called the ternary operator, has the form condition ? valueIfTrue : valueIfFalse. After evaluating condition, it selects the expression after ? for true or after : for false. The unselected branch is not evaluated. Use it for a compact value selection, such as in an assignment or method argument; prefer if/else for more complex logic.
The condition must have type boolean or Boolean. A null value of type Boolean causes NullPointerException during unboxing. Both branches must be valid at compile time; neither may be a call to a method returning void. The result type is determined at compile time, not solely by the selected branch.
The operator is right-associative: a ? b : c ? d : e means a ? b : (c ? d : e). Add parentheses for readability and avoid deep nesting.
Examples
public class ConditionalDemo {
public static void main(String[] args) {
int count = 0;
int total = 12;
int average = count == 0 ? 0 : total / count;
System.out.println(average);
}
}Result
0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.