Ternary Operator
The ternary operator in Java is a conditional operator used to make decisions in a single line of code. It is often used as a compact alternative to if-else statements. This topic is commonly asked in interviews and frequently used in clean, concise Java code.
What Is the Ternary Operator?
- A conditional operator
- Takes three operands
- Returns a value based on a condition
Syntax:
condition ? expression1 : expression2;
How the Ternary Operator Works
- If the condition is true → expression1 is executed
- If the condition is false → expression2 is executed
Basic Example
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println(max); // 20
Ternary Operator vs if-else
Using if-else
int result;
if (a > b) {
result = a;
} else {
result = b;
}
Using Ternary Operator
int result = (a > b) ? a : b;
Why it matters: Ternary operator makes code shorter and more readable for simple conditions.
Using Ternary Operator with Different Data Types
With Strings
String status = (age >= 18) ? "Adult" : "Minor";
With Method Calls
int result = (isValid) ? calculateA() : calculateB();
Nested Ternary Operator (Advanced)
Used for multiple conditions, but should be used carefully.
int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
Interview Tip: Nested ternary is valid but can reduce readability.
Ternary Operator with Assignment
boolean isLoggedIn = true;
String message = isLoggedIn ? "Welcome" : "Please login";
Type Compatibility Rules
- Both expressions must return compatible types
- Java performs type promotion if needed
int x = true ? 10 : 20; // valid
// int x = true ? 10 : 10.5; ❌ invalid
Common Beginner Mistakes
- Using ternary for complex logic
- Forgetting parentheses in nested ternary
- Mixing incompatible return types
- Overusing ternary, reducing readability
Interview-Ready Answers
Short Answer
The ternary operator is a conditional operator used to make decisions in a single line.
Detailed Answer
The ternary operator (? :) evaluates a condition and returns one of two values based on whether the condition is true or false. It is commonly used as a compact alternative to if-else for simple conditional logic.
Key Takeaway
The ternary operator improves code conciseness, but should be used only for simple conditions to maintain readability.