The conditional operator (?:) — The Only Ternary Operator is one of the most useful operators in Java. It lets you write simple decision-making logic in a single line, making your code cleaner and more concise.
It's also a favorite topic in Java interviews because of its syntax, nesting behavior, and type compatibility rules.
In this article, you'll learn:
- What the conditional operator is
- Why it's called a ternary operator
- Syntax and working
- Nested conditional operators
- Difference between
?:andif-else - Practical examples
- Interview questions
- Memory tricks
What is the Conditional Operator?
The conditional operator is represented by:
? :
It is the only ternary operator in Java.
A ternary operator takes three operands, unlike:
| Operator Type | Number of Operands | Example |
|---|---|---|
| Unary | 1 |
++x, !flag, ~5
|
| Binary | 2 |
a + b, a > b, a && b
|
| Ternary | 3 | (a > b) ? a : b |
Syntax
result = (condition) ? valueIfTrue : valueIfFalse;
How It Works
condition
│
Is it true?
/ \
Yes No
│ │
valueIfTrue valueIfFalse
│ │
└────── Result ──────┘
If the condition is true, Java returns the value before the colon (:).
If the condition is false, Java returns the value after the colon (:).
Example 1
int x = (10 > 20) ? 30 : 40;
System.out.println(x);
Output
40
Step-by-Step
Evaluate the condition:
10 > 20
↓
false
Since the condition is false,
Java selects the value after :.
40
Therefore,
x = 40
Example 2: Finding the Maximum
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println(max);
Output
20
This is one of the most common uses of the conditional operator.
Example 3: Even or Odd
int number = 7;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
Output
Odd
Example 4: Absolute Value
int x = -5;
int absolute = (x < 0) ? -x : x;
System.out.println(absolute);
Output
5
Nested Conditional Operators
One of the biggest advantages of the conditional operator is that it can be nested.
Example
int x = (10 > 20)
? 30
: ((40 > 50) ? 60 : 70);
System.out.println(x);
Output
70
Step-by-Step Execution
Outer condition
10 > 20
↓
false
So Java evaluates the false branch.
(40 > 50) ? 60 : 70
Inner condition
40 > 50
↓
false
Therefore,
70
Final result
x = 70
Multiple Nested Conditions
int marks = 75;
String grade =
(marks >= 90) ? "A"
: (marks >= 75) ? "B"
: (marks >= 60) ? "C"
: "F";
System.out.println(grade);
Output
B
This behaves like:
if marks >= 90
↓
Grade A
else if marks >= 75
↓
Grade B
else if marks >= 60
↓
Grade C
else
↓
Grade F
Conditional Operator vs if-else
The conditional operator is simply a compact version of an if-else statement when you need to return or assign a value.
Using if-else
int max;
if (a > b) {
max = a;
} else {
max = b;
}
Using the Conditional Operator
int max = (a > b) ? a : b;
Both produce the same result.
The second version is shorter and easier to read.
When Should You Use ?: ?
Use the conditional operator when:
- You need to assign a value.
- The logic is simple.
- It improves readability.
Avoid deeply nested conditional operators if they make the code difficult to understand.
Rule 1: The Condition Must Be boolean
Valid
int x = (10 > 20) ? 30 : 40;
Invalid
int x = (10) ? 30 : 40;
Compiler Error
incompatible types
found: int
required: boolean
The first operand must always evaluate to a boolean value.
Rule 2: Both Result Expressions Must Be Compatible
Valid
int x = (10 > 20) ? 30 : 40;
Both branches return an int.
Also valid
double d = (10 > 20) ? 30 : 40.5;
The integer 30 is automatically widened to double.
Invalid
int x = (10 > 20) ? 30 : "Hello";
The two result expressions are incompatible.
Rule 3: Nesting Is Allowed
Unlike many operators, the conditional operator supports nesting.
| Operator | Can Be Nested? |
|---|---|
Relational (>, <) |
❌ No |
Increment (++, --) |
❌ No |
Conditional (?:) |
✅ Yes |
Interview Trick Question
int x = (10 > 5)
? (5 > 3 ? 100 : 200)
: (3 > 1 ? 300 : 400);
System.out.println(x);
Output
100
Step-by-Step
Outer condition
10 > 5
↓
true
Evaluate the true branch.
5 > 3 ? 100 : 200
Condition
5 > 3
↓
true
Result
100
Final answer
x = 100
Conditional Operator vs Short-Circuit Operators
Although both skip unnecessary evaluation, they serve different purposes.
💡 Conditional Operator (
?:)
- Operands: 3 (Ternary)
- Returns: Any compatible type (coerced to a common type)
- Purpose: Choose between two values based on a condition.
- Example:
String status = (age >= 18) ? "Adult" : "Minor";⚡ Short-Circuit Operators (
&&,||)
- Operands: 2 (Binary)
- Returns:
boolean- Purpose: Combine boolean expressions safely using lazy evaluation.
- Example:
if (list != null && !list.isEmpty())
Summary Table
| Property | Conditional Operator |
|---|---|
| Symbol | ?: |
| Number of operands | 3 |
| First operand | boolean condition |
| Second operand | Value if true |
| Third operand | Value if false |
| Returns | One value |
| Can be nested | ✅ Yes |
| Used for | Replacing simple if-else assignments |
Quick Reference
Basic Syntax
result = (condition) ? valueIfTrue : valueIfFalse;
Find Maximum
int max = (a > b) ? a : b;
Even or Odd
String parity = (number % 2 == 0) ? "Even" : "Odd";
Nested Example
int result =
condition1
? value1
: condition2
? value2
: value3;
Read it as:
If
condition1is true, returnvalue1; otherwise, ifcondition2is true, returnvalue2; else returnvalue3.
Interview Questions
Which is the only ternary operator in Java?
The conditional operator (?:).
Why is it called a ternary operator?
Because it takes three operands.
Can the conditional operator be nested?
Yes.
Can the condition be an integer?
No.
The first operand must always evaluate to a boolean.
Can the result expressions have different types?
Only if Java can convert them to a common compatible type.
When should you use the conditional operator instead of if-else?
When you need to choose or assign a value based on a simple condition.
Memory Tricks 🧠
Read It Like English
condition ? trueValue : falseValue
If the condition is true, take the value before the colon. Otherwise, take the value after the colon.
Easy Way to Remember
?
↓
Ask a question
:
↓
Otherwise
Think of It As
IF condition
↓
Return this
ELSE
↓
Return that
Key Takeaways
- The conditional operator (
?:) is the only ternary operator in Java. - It evaluates a boolean condition and returns one of two values.
- It provides a concise alternative to simple
if-elsestatements used for value assignment. - The first operand must always evaluate to a boolean.
- Both result expressions must be type-compatible.
- Nested conditional operators are supported, but excessive nesting can reduce readability.
- Use the conditional operator to write cleaner, more expressive Java code for simple decision-making.
Happy Coding!
Top comments (0)