Web Analytics

Ternary Operator

Beginner ~10 min read

The ternary operator (also known as the conditional operator) is a shorthand way to write simple if-else statements. It's the only operator in Java that takes three operands.

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

It works like this:

  1. Evaluate the condition.
  2. If true, execute/return expressionTrue.
  3. If false, execute/return expressionFalse.

Example: Replacing If-Else

Let's find the maximum of two numbers.

Using If-Else

int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

Using Ternary Operator

int max = (a > b) ? a : b;
Output
Click Run to execute your code

Nested Ternary Operators

You can nest ternary operators, but be careful! It can make code hard to read.

// Check if number is positive, negative, or zero
String result = (num > 0) ? "Positive" : ((num < 0) ? "Negative" : "Zero");
Best Practice: Avoid complex nesting. If it's hard to read at a glance, stick to a standard if-else block for clarity.

Summary

  • The ternary operator ? : is a concise replacement for simple if-else blocks.
  • Syntax: condition ? trueVal : falseVal.
  • Both return values must be of compatible data types.
  • Use it for simple assignments to improve readability; avoid it for complex logic.