DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Conditional Operator (`?:`) in Java

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 ?: and if-else
  • Practical examples
  • Interview questions
  • Memory tricks

What is the Conditional Operator?

The conditional operator is represented by:

? :
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

How It Works

           condition
               │
          Is it true?
          /         \
       Yes           No
        │             │
 valueIfTrue    valueIfFalse
        │             │
        └────── Result ──────┘
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output

40
Enter fullscreen mode Exit fullscreen mode

Step-by-Step

Evaluate the condition:

10 > 20

↓

false
Enter fullscreen mode Exit fullscreen mode

Since the condition is false,

Java selects the value after :.

40
Enter fullscreen mode Exit fullscreen mode

Therefore,

x = 40
Enter fullscreen mode Exit fullscreen mode

Example 2: Finding the Maximum

int a = 10;
int b = 20;

int max = (a > b) ? a : b;

System.out.println(max);
Enter fullscreen mode Exit fullscreen mode

Output

20
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output

Odd
Enter fullscreen mode Exit fullscreen mode

Example 4: Absolute Value

int x = -5;

int absolute = (x < 0) ? -x : x;

System.out.println(absolute);
Enter fullscreen mode Exit fullscreen mode

Output

5
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output

70
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Execution

Outer condition

10 > 20

↓

false
Enter fullscreen mode Exit fullscreen mode

So Java evaluates the false branch.

(40 > 50) ? 60 : 70
Enter fullscreen mode Exit fullscreen mode

Inner condition

40 > 50

↓

false
Enter fullscreen mode Exit fullscreen mode

Therefore,

70
Enter fullscreen mode Exit fullscreen mode

Final result

x = 70
Enter fullscreen mode Exit fullscreen mode

Multiple Nested Conditions

int marks = 75;

String grade =
        (marks >= 90) ? "A"
      : (marks >= 75) ? "B"
      : (marks >= 60) ? "C"
      : "F";

System.out.println(grade);
Enter fullscreen mode Exit fullscreen mode

Output

B
Enter fullscreen mode Exit fullscreen mode

This behaves like:

if marks >= 90

↓

Grade A

else if marks >= 75

↓

Grade B

else if marks >= 60

↓

Grade C

else

↓

Grade F
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Using the Conditional Operator

int max = (a > b) ? a : b;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Invalid

int x = (10) ? 30 : 40;
Enter fullscreen mode Exit fullscreen mode

Compiler Error

incompatible types

found: int

required: boolean
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Both branches return an int.


Also valid

double d = (10 > 20) ? 30 : 40.5;
Enter fullscreen mode Exit fullscreen mode

The integer 30 is automatically widened to double.


Invalid

int x = (10 > 20) ? 30 : "Hello";
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output

100
Enter fullscreen mode Exit fullscreen mode

Step-by-Step

Outer condition

10 > 5

↓

true
Enter fullscreen mode Exit fullscreen mode

Evaluate the true branch.

5 > 3 ? 100 : 200
Enter fullscreen mode Exit fullscreen mode

Condition

5 > 3

↓

true
Enter fullscreen mode Exit fullscreen mode

Result

100
Enter fullscreen mode Exit fullscreen mode

Final answer

x = 100
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Find Maximum

int max = (a > b) ? a : b;
Enter fullscreen mode Exit fullscreen mode

Even or Odd

String parity = (number % 2 == 0) ? "Even" : "Odd";
Enter fullscreen mode Exit fullscreen mode

Nested Example

int result =
        condition1
        ? value1
        : condition2
            ? value2
            : value3;
Enter fullscreen mode Exit fullscreen mode

Read it as:

If condition1 is true, return value1; otherwise, if condition2 is true, return value2; else return value3.


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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Think of It As

IF condition

↓

Return this

ELSE

↓

Return that
Enter fullscreen mode Exit fullscreen mode

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-else statements 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)