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 - 1Ternary 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). The usher checks his age at the door: if he passed the age check, he is allowed to enter; if not, he is sent home. Let's declare a Person class and check this using an if-else statement:
public class Person {

   private int age;

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

   public int getAge() {
       return age;
   }

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

   public static void main(String[] args) {

       Person person = new Person(22);

       String usherResponse;

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

       System.out.println(usherResponse);

   }
}
Console output:
"Everything is in order. Come in!"
If we remove the console output, then our check looks like this:
if (person.getAge() >= 18) {
           usherResponse = "Everything is in order. Come in!";
       } else {
           usherResponse = "This film is not suitable for your age!";
       }
The logic is very simple here: one condition is checked (age >= 18) Based on the result, the variable usherResponse is assigned one of two strings with the usher's response. 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) {

   Person person = new Person(22);

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

   System.out.println(usherResponse);

}
Here's how this operator works. It is called the ternary operator, because it involves 3 components:
  • One condition (person.getAge() > 18)
  • 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.
person.getAge() > 18 ?
"Is this person's age more than 18?" Then we write the first value. This value is used if the condition evaluates to true:
String usherResponse = person.getAge() > 18 ? "Everything is in order. Come in!"
Is this person's age more than 18? If yes, set the usherResponse 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 usherResponse = person.getAge() > 18 ? "Everything is in order. Come in!" : "This film is not suitable for your age!";
Is this person's age more than 18? If yes, set the usherResponse variable to "Everything is in order. Come in!". If not, set the usherResponse variable to "This film is not suitable for your age!" In general, here's what the ternary operator's logic looks like. condition ? outcome 1 : outcome 2 Ternary operator - 2By the way, the parentheses around the condition are not required: we added them for greater readability. It also works without them:
public static void main(String[] args) {

   Person person = new Person(22);

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

   System.out.println(usherResponse);

}
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 biggest consideration here is the readability of your code. 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). Ternary operator - 3The general recommendation is this: 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 usherResponse = (person.getAge() > 18 && (person.hasTicket() || person.hasCoupon()) && !person.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 18, 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 your colleagues won't face palm if they inherit this code :) Finally, I can recommend a good for you. We touched on code readability during the lesson. Robert Marin's book "Clean Code", which has become a classic, is dedicated to this topic. Ternary operator - 4It brings together best practices and recommendations for programmers, which will help you write code that is not only functional, but also easily readable.