2️⃣

# 7.2 Ternary Operator

⚒️
Ch. 7 Other Selection Structures

## Ternary Operator

The final selection structure we’ll learn in this course is the ternary operator. There is only one ternary operator in Java; that is, there is only one operator in Java that operates on 3 things. It is like a basic if-else statement that you can write in one line. It is not very common, but you may see it in programs, so it’s good to be familiar with how it works.
Let’s say you need to assign a value to a variable depending on a condition. In the example below, there is a variable `days` which stores the number of days in February, which can either be 28 or 29 (depending on if it is a leap year). You can use an if-else statement to assign a value to days, like so:
``````if (isLeapYear) {
days = 29;
} else {
days 28;
}``````

Alternatively, you can use a ternary operator, like so:
``````// same as above, but shorter
days = isLeapYear ? 29 : 28;``````

As you can see, the general form of a ternary operator is:
``condition ? trueResult : falseResult``
In the code above, if `isLeapYear` is `true``days` is assigned to 29. Otherwise, it is assigned to 28.

1️⃣
7.1 Switch

3️⃣
7.3 Practice

⚖️