Java ProgramsBasics & I/ODemonstrate Ternary Operator

Demonstrate Ternary Operator in Java

beginner·  Basics & I/O  ·  Operators

Problem

The ternary operator (condition ? valueIfTrue : valueIfFalse) is Java's only operator that takes three operands, letting a simple if-else that just assigns a value be written as one expression instead of four lines.

Given two integers, use the ternary operator to determine and print the larger one.

Input
10, 20
Output
Larger: 20

Java Program

Java
public class DemonstrateTernaryOperator { public static void main(String[] args) { int a = 10; int b = 20; int larger = (a > b) ? a : b; // picks a if the condition is true, otherwise b System.out.println("Larger: " + larger); } }

Output

Larger: 20

Core Logic

The ternary operator evaluates the condition once and immediately produces one of two values, without needing a separate variable declared outside an if-else block.

How It Works
  1. 1a > b is the condition — it's evaluated first.
  2. 2If the condition is true, the whole expression evaluates to the value right after ?, which is a.
  3. 3If the condition is false, the expression evaluates to the value after : instead, which is b.
  4. 4Since a = 10 and b = 20, a > b is false, so the whole expression evaluates to b, 20.
For a = 10 and b = 20: a > b is false, so (a > b) ? a : b evaluates to 20.
💡

Key Point: (a > b) ? a : b is exactly equivalent to if (a > b) { result = a; } else { result = b; } — the ternary form is shorter only because both branches do nothing but produce a value.

Key Concepts

ternary operator? : operatorconditional expression

Related Programs