Skip to lesson

The ternary operator ?:

The ternary operator ?: picks one of two values using a condition. marks >= 35 ? "Pass" : "Fail" gives "Pass" when the condition is true and "Fail" when it is false.

How ?: works

A result card must show "Pass" or "Fail", but marks >= 35 gives only true or false.

Syntax
condition ? valueIfTrue : valueIfFalse

Java checks the condition first: if it is true, the answer is the value after ?; if false, the value after :. It is called ternary because it has three parts.

marks is 42, so marks >= 35 is true and the ternary operator gives "Pass", the value after the question mark. "Fail", the value after the colon, is not used.

Experiment

Pass mark

Slide marks across 35 and watch the answer switch.

int marks = 42;
String result = marks >= 35 ? "Pass" : "Fail";
System.out.println(result);
marks >= 35
true
result
Pass

Picking a number with ?:

A cinema charges students Rs 100 and everyone else Rs 200. ?: picks between two numbers the same way it picks between two words.

Example · Ticket price and the bigger number

Ticket.javaJava
public class Ticket {    public static void main(String[] args) {        boolean isStudent = true;        int fee = isStudent ? 100 : 200;        System.out.println("Ticket: Rs " + fee);        int a = 45;        int b = 72;        int bigger = a > b ? a : b;        System.out.println("Bigger: " + bigger);    }}
Output
Ticket: Rs 100
Bigger: 72

What this code does

  • The condition can be a boolean variable. isStudent is true, so fee gets 100.
  • It can also be a comparison: a > b is false, so bigger gets b, which is 72. This is a handy way to find the bigger of two numbers.

Both results need the same type

A shop label should say "In stock" or show 0, but one String variable cannot hold text one time and a number the next.

Java
boolean isStudent = true;int marks = 40;int fee = isStudent ? 100 : 200;       // both int: fineString r = marks >= 35 ? "Pass" : 0;   // error: bad type in conditional expression

The two results are called branches, and both need the same type.

Mixing int and double compiles but surprises you: isStudent ? 1 : 2.5 gives a double, so even the 1 comes out as 1.0.

Use ?: for a small choice between two values, and do not put one ?: inside another. When there is more to do, if-else (opens in a new tab) is clearer.

Next step

Check your understanding

8 quick questions