JavaRush /Java Blog /Random EN /Ternary operator in Java

Ternary operator in Java

Published in the Random EN group
Hello! Today's lecture will not be very long, but definitely useful :) We will talk about the so-called ternary operator . Ternary operator - 1"Ternary" in translation means "triple". This is an alternative to the conditional operator if-elseyou are already familiar with. Let's take an example. Let's say a person decides to go to the cinema to see a movie with an 18+ rating. The guard checks his age at the entrance: if he passes the age limit, he allows him to enter the hall, if not, he sends him home. Let's create a class Manand test it with if-else:
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() >= 18) {
           securityAnswer = "It's all right, come in!";
       } else {
           securityAnswer = "This movie is not suitable for your age!";
       }

       System.out.println(securityAnswer);

   }
}
Console output:

"Все в порядке, проходите!"
If we remove the output to the console, our check looks like this:
if (man.getAge() >= 18) {
           securityAnswer = "It's all right, come in!";
       } else {
           securityAnswer = "This movie is not suitable for your age!";
       }
Here, in fact, simple logic works: one condition is checked (age >= 18). Depending on this, securityAnswerone of the two strings with the guard's response is assigned to the variable. Such situations, “one condition - two possible outcomes”, are very common in programming. Therefore, the same ternary operator was created for them. With it, we can simplify our check to a single line of code:
public static void main(String[] args) {

   Man man = new Man(22);

   String securityAnswer = (man.getAge() >= 18) ? "It's all right, come in!" : "This movie is not suitable for your age!";

   System.out.println(securityAnswer);

}
This is what this operator looks like. It is called ternary (triple) because 3 components take part in its work:
  • One condition ( man.getAge() >= 18)
  • Two possible outcomes ( "It's okay, come on!" and "This movie is not suitable for your age!" )
First, a condition is written in the code, followed by a question mark.
man.getAge() >= 18 ?
“Is the person's age greater than or equal to 18?” The first result follows. It fires if the condition returns true, i.e. is true:
String securityAnswer = man.getAge() >= 18 ? "It's all right, come in!"
Is the person's age greater than or equal to 18? If so, set the variable to securityAnswer " It's all right, move on!" . This is followed by the “ :” operator, after which the second result is written. It fires if the condition returns false, i.e. is false:
String securityAnswer = man.getAge() >= 18 ? "It's all right, come in!" : "This movie is not suitable for your age!";
Is the person's age greater than or equal to 18? If so, set the variable to securityAnswer " It's all right, move on!" . If not, set the variable to securityAnswer " This movie is not suitable for your age!" This is how the general logic of the ternary operator looks like. condition ? result 1 : result 2 Ternary operator - 2By the way, parentheses around the condition are optional: we did it for greater readability. Works without them:
public static void main(String[] args) {

   Man man = new Man(22);

   String securityAnswer = man.getAge() >= 18 ? "It's all right, come in!" : "This movie is not suitable for your age!";

   System.out.println(securityAnswer);

}
What to use anyway: if-else, or the ternary operator? In terms of performance, there is not much difference. More precisely, maybe it is, but insignificant. Here the question relates more to the readability of your code. It is extremely important in programming: the code you write should not only work correctly, but also be easy to read. After all, it can be “inherited” to other programmers, your colleagues! And if it is difficult to understand, it will complicate both their work and yours - they will run to you for explanations every 5 minutes. A general recommendation might sound like this: if the condition is simple and easy to check, you can safely use the ternary operator. Thus, you will reduce the amount of code and the number of checksif-else, of which there may already be many. But if the condition is complex and multi-stage, it is better to use if-else. For example, in this case, using the ternary operator would be a bad idea:
String securityAnswer = (man.getAge() >= 18 && (man.hasTicket() || man.hasCoupon()) && !man.hasChild())  ? "Come in!" : "You can not pass!";
So right off the bat and do not understand what is happening here! The code has become very difficult to read. And all because of a difficult condition:
  • If a person is over or equal to 18 years old + they have a ticket (or they have a coupon for free admission) + they do not have small children with them - then they can pass.
  • If at least one of the parts of the condition returns false, then it cannot.
Here it would be better to use if-else. Yes, our code would become larger in size, but it would be many times more readable. And none of the colleagues will grab his head if he inherits such a code :) Ternary operator - 3Finally, I can recommend you a book. We touched on the topic of code readability in the lecture. The classic book “Clean Code” by Robert Martin is dedicated to it. Ternary operator - 3It contains best practices and recommendations for programmers that will allow you to write not only working, but also easy to read code. There is a review of this book on CodeGym.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION