Flash cards
Review the key moves
What is the main idea behind Java Short Hand If...Else (Ternary Operator)?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ = ( condition ) ? expressionTruePut the learning moves in the order that makes the concept easiest to apply.
Short Hand if...else
There is also a short-hand if else , which is known as the ternary operator because it consists of three operands.
It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements:
Syntax
variable = ( condition ) ? expressionTrue
: expressionFalse ;Example
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}Example
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);You can simply write
You can also use the ternary operator directly inside System.out.println() without a temporary variable:
Example
int time = 20;
System.out.println((time < 18) ? "Good day." : "Good evening.");Nested Ternary (Optional)
You can nest ternary operators to handle more than two possible outcomes, but this can make your code harder to read:
Example
int time = 22;
String message = (time < 12) ? "Good morning."
: (time < 18) ? "Good afternoon."
: "Good evening.";
System.out.println(message);Tip
Use the ternary operator for short, simple choices. For longer or more complex logic, the regular if...else is easier to read.