⬅ Previous Topic
Java Switch StatementNext Topic ⮕
Java Loops⬅ Previous Topic
Java Switch StatementNext Topic ⮕
Java LoopsThe 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.
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
.
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
age >= 18
true
, so the result is assigned "Eligible to vote"
System.out.println()
prints the resultYou 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
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".
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.
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.
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.
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.
int a = 5, b = 10;
int result = (a > b) ? a : b;
System.out.println(result);
int num = 0;
String type = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
System.out.println("The number is " + type);
⬅ Previous Topic
Java Switch StatementNext Topic ⮕
Java LoopsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.