Skip to content

The Ternary Operator

A ternary operator allows our program to return results based on a condition being true or false in a single line reducing the number of lines required to execute this function. Below is an example of a ternary operator:

int income = 120_000;
String className = income > 100_000 ? "First" : "Economy";

Here we are setting the return value of className a String by evaluating if our income value is greater than 100,000. A ternary is structured as:

condition ? (Question mark to denote the ternary operation) Truth Value : (Colon to represent the split to a false value) False Value

String returnedValue = initialValue < benchmarkValue ? "Truth" : "False";