AI Hints
Home›Java Tutorial›Logical Operators, The Ternary Operator and switch
Java · Lesson 32 of 120

The Ternary Operator

If and else in one line.

⏱ 2 min read▶ Video at 41:50🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

When you just need to pick one of two values, an if and else feels long. The ternary operator does it in one line.

  • Pick one of two values
  • Condition ? a : b
  • One line

Choosing a value

A condition, then a question mark. The value after it is used when the condition is true. The value after the colon, when it's false. It's perfect for small choices, like item or items. Or picking the bigger of two numbers. Run it. Seventy two is a pass. One item, three items. And thirteen is bigger.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int score = 72;
        String result = score >= 50 ? "pass" : "fail";
        System.out.println("Result: " + result);

        int items = 1;
        System.out.println(items + (items == 1 ? " item" : " items"));
        items = 3;
        System.out.println(items + (items == 1 ? " item" : " items"));

        int a = 8, b = 13;
        int bigger = a > b ? a : b;
        System.out.println("Bigger: " + bigger);
    }
}
Output
Result: pass
1 item
3 items
Bigger: 13

Ternary or if

Use the ternary operator to choose between two simple values. Use if and else when you need to run several statements, or when the logic is complicated. Readability always wins.

Ternary

  • Pick one of two valuesFits on one linex ? a : b

if / else

  • Run several statementsComplex logicEasier to read

Summary

Condition, question mark, value if true, colon, value if false. Use it for small choices. Next, switch.

Key takeaways
  • cond ? a : b
  • Small choices
  • Readability wins
Next up: switch — choosing from many cases