Java Ternary Operator
Conditional Logic in One Line
What is the Java Ternary Operator?
The ternary operator in Java is a concise, elegant way to perform conditional logic. Instead of writing a full if-else block, you can evaluate a condition in a single line and return one of two results based on whether the condition is true or false.
Syntax of the Ternary Operator
The ternary operator uses three operands—hence the name "ternary". Here's the basic structure:
condition ? expressionIfTrue : expressionIfFalse;
If the condition
is true, the value of the whole expression becomes expressionIfTrue
. Otherwise, it becomes expressionIfFalse
.
Simple Example
public class TernaryExample {
public static void main(String[] args) {
int age = 18;
String result = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
System.out.println(result);
}
}
Eligible to vote
Step-by-Step Breakdown
- We check if
age >= 18
- The condition is
true
, so the result is assigned"Eligible to vote"
System.out.println()
prints the result
Using Ternary with Numbers
You can use it to assign values dynamically based on a condition:
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max);
Maximum: 20
Nested Ternary Operators
Though not always recommended for readability, you can nest ternary operators:
int num = 0;
String type = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
System.out.println("The number is " + type);
The number is Zero
This reads like: if num > 0
, return "Positive", else if num < 0
, return "Negative", else return "Zero".
When to Use the Ternary Operator
The ternary operator shines in simple, straightforward decisions. It's especially handy when you want to assign a value based on a condition—without cluttering your code with verbose if-else blocks.
Avoid Overcomplicating
If your logic involves multiple conditions, calculations, or side effects (like printing or database calls), stick to traditional if-else
statements for clarity and maintainability.
Real-World Example
public class DiscountCalculator {
public static void main(String[] args) {
boolean isMember = true;
double price = 250.0;
double discount = isMember ? 0.15 : 0.05;
double finalPrice = price - (price * discount);
System.out.println("Final Price: " + finalPrice);
}
}
Final Price: 212.5
Here, the discount is applied based on membership status. Simple and clean.
Conclusion
The Java ternary operator can be a powerful tool in your coding arsenal—when used wisely. It helps you write less, do more, and keep your logic sharp and succinct. But like all sharp tools, it should be wielded with care—prefer readability over cleverness.
QUIZ
Question 1:What is the correct syntax of the ternary operator in Java?
Question 2:The ternary operator can completely replace all if-else statements in Java.
Question 3:What will the following code output?
int a = 5, b = 10;
int result = (a > b) ? a : b;
System.out.println(result);
int a = 5, b = 10;
int result = (a > b) ? a : b;
System.out.println(result);
Question 4:Which of the following are appropriate use cases for the ternary operator?
Question 5:Consider the code below. What will be printed?
int num = 0;
String type = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
System.out.println("The number is " + type);
int num = 0;
String type = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
System.out.println("The number is " + type);