← Back to Chapters

Java Ternary Operator

⚡ Java Ternary Operator

? Quick Overview

The ternary operator in Java is a shorthand way to write simple if-else conditions in a single line. It makes code shorter, cleaner, and easier to read when used correctly.

? Key Concepts

  • Also called the conditional operator
  • Uses ? and : symbols
  • Returns a value based on a condition
  • Best for simple decision-making logic

? Syntax / Theory

The ternary operator evaluates a condition and returns one of two values.

Syntax

? View Code Example
// General syntax of ternary operator
result = (condition) ? valueIfTrue : valueIfFalse;

? Code Example(s)

? View Code Example
// Check which number is greater using ternary operator
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println(max);

? Live Output / Explanation

Output

20

The condition a > b is false, so the value of b is assigned to max.

✅ Tips & Best Practices

  • Use ternary operators for simple conditions only
  • Avoid nesting ternary operators to keep code readable
  • Prefer if-else for complex logic

? Try It Yourself

  • Use ternary operator to check if a number is even or odd
  • Find the minimum of two numbers
  • Assign grades based on marks using ternary operator