Ternary Operator Example in Java

Ternary operator is a conditional operator which has three operands. It is best replacement one-liner for simple if-else statement.

The first operand of ternary operator is a boolean value or expression that returns boolean value. In the next two operands (or statements), either of the operand will be executed based on the value of first  operand.

The below Program illustrates the working principles of ternary operator.


Program or Solution


class Ternary


public static void main(String args[])


int a = 10;

int b = 20;

int c = a>b?a:b;






Ternary Operator Example in Java Output

Program Explanation

In the First println() a is not greater than b so c is 20.

In the second println() first operand is true so it prints "Decode"