Hi! Today's lesson won't be very long, but it will definitely be useful :) We're going to talk about the so-called ternary operator.
Ternary operator - 1
Ternary means "composed of three parts". It is an alternative to the if-else control flow statement that you've already met. Let's give an example. Suppose someone decided to go to an R-rated movie (under 17 requires an accompanying parent or adult guardian). An attendant checks his age at the entrance: if he passes the age check, he is allowed to enter; if not, he is sent home. Let's declare a Man class and check this using an if-else statement:
public class Man {

   private int age;

   public Man(int age) {
       this.age = age;
   }

   public int getAge() {
       return age;
   }

   public void setAge(int age) {
       this.age = age;
   }

   public static void main(String[] args) {

       Man man = new Man(22);

       String securityAnswer;

       if (man.getAge() >= 17) {
           securityAnswer = "Everything is in order. Come in!";
       } else {
           securityAnswer = "This film is not suitable for your age!";
       }

       System.out.println(securityAnswer);

   }
}
Console output: "Everything is in order. Come in!" Now our check looks like this (after removing the console output):
if (man.getAge() >= 17) {
           securityAnswer = "Everything is in order. Pass!";
       } else {
           securityAnswer = "This film is not suitable for your age!";
       }
The logic is very simple here: one condition is checked (age > 16) and, based on the result, the variable securityAnswer is assigned one of two strings with the attendant's answer. Such situations ("one condition - two possible outcomes") are extremely common in programming. And that's why the ternary operator was created. We can use it to simplify our check to a single line of code:
public static void main(String[] args) {

   Man man = new Man(22);

   String securityAnswer = (man.getAge() > 16) ? "Everything is in order. Come in!" : "This film is not suitable for your age!";

   System.out.println(securityAnswer);

}
Here's how this operator works. It is called the ternary operator, because it involves 3 components:
  • One condition (man.getAge() > 16)
  • Two possible outcomes ("Everything is in order. Come in!" and "This film is not suitable for your age!")
First, we write the condition, followed by a question mark.
man.getAge() > 16 ?
"Is this person's age more than 16?" Then we write the first value. This value is used if the condition evaluates to true:
String securityAnswer = man.getAge() > 16 ? "Everything is in order. Come in!"
Is this person's age more than 16? If yes, set the securityAnswer variable to "Everything is in order. Come in!" Next comes the ":" symbol and the second value. This value is used if the condition evaluates to false:
String securityAnswer = man.getAge() > 16 ? "Everything is in order. Come in!" : "This film is not suitable for your age!";
Is this person's age more than 16? If yes, set the securityAnswer variable to "Everything is in order. Come in!". If not, set the securityAnswer variable to "This film is not suitable for your age!" In general, here's what the ternary operator's logic looks like. condition ? value 1 : value 2
Ternary operator - 2
By the way, we don't have to put parentheses around the condition. We only did this for greater readability. It works without them:
public static void main(String[] args) {

   Man man = new Man(22);

   String securityAnswer = man.getAge() > 16 ? "Everything is in order. Come in!" : "This film is not suitable for your age!";

   System.out.println(securityAnswer);

}
Okay, so what should you use: an if-else statement or the ternary operator? In terms of performance, there's no difference. More accurately, maybe there is, but it's insignificant. The main question here is most likely about the readability of your code. This issue is extremely important in programming: the code you write must not only work correctly, but also be easy to read. After all, it might be "inherited" by other programmers, your colleagues! If it's difficult to understand, it will complicate their work, and yours (they'll come running to you for explanations every 5 minutes). In general, this is what we recommend: if the condition is simple and easily verified, you can use the ternary operator without harm. This lets you reduce the amount of code and the number of if-else statements (and there might already be lots of them). But if the condition is complex and involves multiple steps, it's better to use an if-else statement. For example, using a ternary operator would be a bad idea in this case:
String securityAnswer = (man.getAge() > 17 && (man.hasTicket() || man.hasCoupon()) && !man.hasChild())  ? "Come in!" : "You can't come in!";
It's not immediately apparent what is happening here! The code has become very difficult to read. And all because of the complex condition:
  • If someone is older than 16, has a ticket (or a free pass), and has no young children, he can come in.
  • If even one part of the condition is false, then he can't.
Here it's clearly better to use if-else. Yes, our code will be bigger, but it will be a lot more readable. And our colleagues won't face palm if they inherit this code :) In conclusion, I can recommend a book for future reading: Clean Code by Robert Martin. We touched on code readability in this lesson, and this book, which has already become a classic, is devoted to this topic.
Ternary operator - 3
It brings together best practices and recommendations for programmers, which will help you write code that is not only functional, but also easily readable.