Ternary Operator

Ternary Operator

A school program needs reliable data and clear rules. The conditional operator chooses one of two values. It is useful for a short report label when a full if-else statement would obscure a simple value choice.

  1. Understand

    The conditional operator chooses one of two values.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Only the selected expression is evaluated. Deeply nested conditional expressions make a report rule harder to read.

What is the Java Ternary Operator?

The ternary operator in Java is a shortcut for simple if else decisions. It lets you check a condition and choose between two values in one line. Use it when you only need to pick between two options, not for complex logic.

Syntax of the Ternary Operator

The ternary operator uses three operands—hence the name "ternary". Here's the basic structure:

condition ? expressionIfTrue : expressionIfFalse;

If the condition is true, the value of the whole expression becomes expressionIfTrue. Otherwise, it becomes expressionIfFalse.

Simple Example for Ternary Operator

Here, the program checks if age is greater than or equal to 18. If it is, it assigns "Eligible to vote" to the result variable; otherwise, it assigns "Not eligible to vote". The result is then printed.

public class TernaryExample {
    public static void main(String[] args) {
        int age = 18;
        String result = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
        System.out.println(result);
    }
}
Eligible to vote

Using Ternary with Numbers

In this example, we find the maximum of two numbers: a and b, using ternary operator.

We compare two numbers, a and b. If a is greater than b, the variable max will get the value of a; otherwise, it will get the value of b.

public class TernaryExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int max = (a > b) ? a : b;
        System.out.println("Maximum: " + max);
    }
}
Maximum: 20

Nested Ternary Operators

The ternary operator can also be nested to handle more than two conditions. This means placing one ternary operator inside another.

In this example, we check if the number is positive, negative, or zero. The first condition checks if num > 0. If true, it returns "Positive". If not, it moves to the second condition: num < 0. If that's true, it returns "Negative". Otherwise, it returns "Zero".

public class NestedTernaryExample {
    public static void main(String[] args) {
        int num = 0;
        String type = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
        System.out.println("The number is " + type);
    }
}
The number is Zero

This reads like: if num > 0, return "Positive", else if num < 0, return "Negative", else return "Zero".

When to Use the Ternary Operator

The ternary operator shines in simple, straightforward decisions. It's especially handy when you want to assign a value based on a condition—without cluttering your code with verbose if-else blocks.

Avoid Overcomplicating

If your logic involves multiple conditions, calculations, or side effects (like printing or database calls), stick to traditional if-else statements for clarity and maintainability.

Real-World Example - Discount Calculator

When calculating prices in an online store or billing system, it's common to offer different discounts to different types of customers. For instance, members might get a bigger discount than non-members. Instead of writing a full if-else block to apply the discount, we can simplify the logic using a ternary operator

If customer is already a member, that is isMember is true, the customer gets a 15% discount. If not, they get only 5%. The ternary operator helps apply the correct discount and calculate the final price in a single line of code.

class DiscountCalculator {
    public static void main(String[] args) {
        boolean isMember = true;
        double price = 250.0;
        double discount = isMember ? 0.15 : 0.05;
        double finalPrice = price - (price * discount);
        System.out.println("Final Price: " + finalPrice);
    }
}
Final Price: 212.5

Here, the discount is applied based on membership status. Simple and clean.

Important boundaries and mistakes

Only the selected expression is evaluated. Deeply nested conditional expressions make a report rule harder to read.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Only the selected expression is evaluated.

Java 17 · Main.java · complete practice program

public class Main  {
  public static void main(String[] args)  {
    int marks = 72;
    String result = marks >= 50 ? "Pass" : "Practise";
    System.out.println(result);
  }
}

Now change one thing: Change marks to 40. Predict the new behavior before checking the worked variation.

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  public static void main(String[] args)  {
    int marks = 72;
    String result = marks >= 50 ? "Pass" : "Practise";
    System.out.println(result);
  }
}

Expected output

Pass

The conditional operator chooses one of two values. It is useful for a short report label when a full if-else statement would obscure a simple value choice.

Only the selected expression is evaluated. Deeply nested conditional expressions make a report rule harder to read.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Worked variation: Change marks to 40. The expression chooses Practise.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

Pass

The conditional operator chooses one of two values. It is useful for a short report label when a full if-else statement would obscure a simple value choice. Only the selected expression is evaluated. Deeply nested conditional expressions make a report rule harder to read.

What to remember

The conditional operator chooses one of two values. It is useful for a short report label when a full if-else statement would obscure a simple value choice. Only the selected expression is evaluated. Deeply nested conditional expressions make a report rule harder to read.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Loops →