Chapter Table of Contents

Ch. 7 Other Selection Structures

Section Table of Contents

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 truedays is assigned to 29. Otherwise, it is assigned to 28.

🖥️ TernaryOperator.java

Previous Section

7.1 Switch

Next Section

7.3 Practice

<aside> ⚖️ Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License.

If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact [email protected] for inquiries.

</aside>