The Ternary Operator: Syntax and Basic Usage
What you'll learn: How to write compact conditional expressions using Java's ternary operator as a shorthand for simple if-else logic.
What Is the Ternary Operator?
The ternary operator is Java's only three-part operator, providing a concise way to choose between two values based on a condition. Think of it as asking a yes-or-no question and getting one of two possible answers instantly.
The Syntax
The ternary operator follows this pattern:
condition ? valueIfTrue : valueIfFalse
- condition: A boolean expression (like
x > 10orisReady) - ?: Separates the condition from the true value
- valueIfTrue: The result if the condition is
true - : Separates the two possible values
- valueIfFalse: The result if the condition is
false
How It Works
int age = 20;
String status = age >= 18 ? "adult" : "minor";
// status is now "adult"
This replaces what would otherwise require multiple lines of if-else logic. The condition age >= 18 evaluates to true, so the operator returns "adult".
You can use it with any compatible types:
int score = 85;
char grade = score >= 90 ? 'A' : 'B'; // grade is 'B'
boolean hasLicense = true;
int discount = hasLicense ? 10 : 0; // discount is 10
The key advantage: the ternary operator is an expression that produces a value, making it perfect for assignments or passing arguments directly.
Key Takeaway: The ternary operator condition ? valueIfTrue : valueIfFalse provides a compact, readable way to choose between two values based on a boolean condition—use it for simple, straightforward choices.