Ternary Operator

Naveen AnamaneniUpdated · 4 min read

At a cinema ticket counter: "Under 12? Child ticket. Otherwise, adult ticket." That's one question and two possible answers. Java has an operator built for exactly this: the ternary operator, condition ? valueIfTrue : valueIfFalse. It's called ternary because it takes three parts, and it lets you pick between two values in a single expression.

How It Works

condition ? value if true : value if false
Ticket.java▶ Try it
public class Ticket {
    public static void main(String[] args) {
        int age = 9;
        String type = age < 12 ? "Child" : "Adult";
        int price = age < 12 ? 120 : 250;
        System.out.println(type + " ticket: Rs. " + price);
    }
}
Output
Child ticket: Rs. 120

How it works

  1. Line 4 checks age < 12. It's true for 9, so the whole expression becomes "Child", the value after ?.
  2. Line 5 asks the same question and picks 120.
  3. If age were 30, the values after : would be chosen: "Adult" and 250.

Try it yourself: change age to 12. Which ticket do you get, and why?

Ternary vs if-else

The ternary on line 4 does the same job as this if-else:

TicketIf.java
String type;
if (age < 12) {
    type = "Child";
} else {
    type = "Adult";
}
Use the ternary whenUse if-else when
You're choosing between two valuesYou're choosing between two actions (printing, saving, calling methods)
Both values are shortEither branch needs several lines
It fits comfortably on one lineThere are more than two cases

You'll learn if-else properly in "Java If-Else Statements".

Result Type

Both sides of a ternary should have the same type, or types Java can combine. When they're different numeric types, the usual promotion rules apply:

Mixed.java▶ Try it
public class Mixed {
    public static void main(String[] args) {
        boolean member = true;
        double discount = member ? 10 : 2.5;
        System.out.println("Discount: " + discount + "%");
    }
}
Output
Discount: 10.0%

The two possible values are 10 (an int) and 2.5 (a double), so the result is a double, and 10 prints as 10.0.

Common Mistakes

Using a ternary for actions. age < 12 ? System.out.println("Child") : System.out.println("Adult"); doesn't compile, because println returns nothing. Use if-else for actions.

Forgetting that only one side runs. Only the chosen value is evaluated, so a method call on the other side never happens. That's usually what you want, but it surprises people while debugging.

Getting the order wrong. It's always condition ? ifTrue : ifFalse. A quick check: the true value sits next to the question mark.

Practice

  1. Easy: Use a ternary to print "Pass" when marks are 35 or more, and "Fail" otherwise.
  2. Harder: Use a ternary to set the delivery charge to 0 when the order total is Rs. 499 or more, and Rs. 40 otherwise. Print the final amount for totals of 450 and 520.

Quick check: Ternary operator

4 questions
1What does 5 > 3 ? "yes" : "no" give?
2How many operands does the ternary operator take?
3What is the type of flag ? 10 : 2.5?
4When is if-else a better choice?

Key Takeaways

Was this tutorial helpful?

Lesson 43 of 482