Section 4.6 The Ternary Operator
The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions.
Java also provides the ternary operator
condition ? valueIfTrue : valueIfFalse, which lets you use a boolean test directly inside an assignment. If the condition is true, the first value is chosen; otherwise, the second value is used. The table below summarizes how it works:
| Component | Description |
condition |
The boolean expression that is evaluated (e.g., a % 2 == 0). |
? |
This is the ternary operator that separates the condition from the trueValue. |
trueValue |
The value assigned if the condition is true (e.g., a * a). |
: |
This is the ternary operator that separates the trueValue from the falseValue. |
falseValue |
The value assigned if the condition is false (e.g., 3 * x - 1). |
| Example Usage | a = a % 2 == 0 ? a * a : 3 * x - 1 |
| Equivalent if-else Code | Can also be written with a regular if-else statement, but the ternary form is more concise. |
Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. See the following as an example where we see the same logic implemented in two different ways.
In this example we are using this ternary operator to assign a value to
a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions.
You have attempted of activities on this page.
