Skip to main content

Section 4.2 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. Tableย 4.2.1 summarizes how it works.
Table 4.2.1. Ternary Operator in Java
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. Listingย 4.2.2 shows an example where we see the same logic implemented in two different ways.
Listing 4.2.2.
In Listingย 4.2.2, 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.

Checkpoint 4.2.3.

Rearrange the blocks to create a Java method that calculates shipping costs. Orders over $100 get free shipping ($0.0), while members pay $5.0 and non-members pay $10.0.
You have attempted of activities on this page.