Ternary Operator (? :
) in Java
The ternary operator is a shorthand for if-else
statements. It allows you to write conditional expressions in a single line.
1. Syntax of the Ternary Operator
condition ? value_if_true : value_if_false;
If condition
is true, the expression returns value_if_true
. If condition
is false, the expression returns value_if_false
.
Example: Simple Ternary Operator
public class TernaryExample {
public static void main(String[] args) {
int num = 10;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(result); // Output: Even
}
}
✔ Equivalent to:
if (num % 2 == 0) {
result = "Even";
} else {
result = "Odd";
}
✔ Ternary operator makes the code shorter and cleaner.
3. Ternary Operator with Method Calls
You can use the ternary operator to call different methods based on a condition.
Example
public class TernaryMethodExample {
public static void main(String[] args) {
int age = 18;
System.out.println(age >= 18 ? "Adult" : "Minor");
}
}
✔ This replaces:
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
4. Nested Ternary Operators
You can nest ternary operators for multiple conditions.
Example
public class NestedTernaryExample {
public static void main(String[] args) {
int num = 0;
String result = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
System.out.println(result); // Output: Zero
}
}
✔ Equivalent to:
if (num > 0) {
result = "Positive";
} else if (num < 0) {
result = "Negative";
} else {
result = "Zero";
}
✔ Be careful! Nesting ternary operators can make the code harder to read.
5. Using the Ternary Operator with Assignments
The ternary operator can assign values based on conditions.
Example
public class AssignmentTernaryExample {
public static void main(String[] args) {
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Max: " + max); // Output: Max: 20
}
}
✔ Equivalent to:
int max;
if (a > b) {
max = a;
} else {
max = b;
}
✔ Ternary operator simplifies variable assignments.
6. When to Use the Ternary Operator
✅ Use it when expressions are simple (like assigning a value or printing output).
✅ It’s best for short and clear conditions.
❌ Avoid nesting ternary operators if it reduces readability.
❌ Use if-else
statements for complex logic instead of deep nesting.