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” means “triple”. This is an alternative to the conditional operator if-else, which you are already familiar with. Let's give an example. Let's say a person decides to go to the cinema to see a film with an 18+ rating. The guard checks his age at the entrance: if he meets the age limit, he allows him to enter the hall; if not, he sends him home. Let's create a class Manand check 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 test 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 two lines with the guard’s response is assigned to the variable. Such situations, “one condition - two possible results,” occur very often in programming. Therefore, the same ternary operator was created for them. With it, we can simplify our verification to one 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 the work of 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, move 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 following is the first result. It fires if the condition returns true, that is, 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 yes, assign the variable securityAnswer the value “Everything is fine, come in!” . This is followed by the “ :” operator, after which the second result is written. It fires if the condition returns false, that is, it 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 yes, assign the variable securityAnswer the value “Everything is fine, come in!” . If not, assign the variable securityAnswer the value “This movie is not suitable for your age!” This is what the general logic of the ternary operator looks like. condition ? result 1 : result 2 Ternary operator - 2By the way, it is not necessary to put parentheses around the condition: we did this for greater readability. It will work 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 should you use: if-else, or the ternary operator? In terms of performance there is not much difference. More precisely, it may exist, but it is insignificant. Here the question relates rather to the readability of your code. It is extremely important in programming: the code you write must 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 use the ternary operator without harm. This way you will reduce the amount of code and the number of checks if-else, of which there may already be a lot. But if the condition is complex and multi-stage, it is better to use if-else. For example, in this case it would be a bad idea to use the ternary operator:

String securityAnswer = (man.getAge() >= 18 && (man.hasTicket() || man.hasCoupon()) && !man.hasChild())  ? "Come in!" : "You can not pass!";
So you won’t immediately understand what’s going on 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 + has a ticket (or has a coupon for free admission) + does not have small children with them - then they can pass.
  • If at least one part of the condition returns false, then it cannot.
This is where it would clearly be better to use if-else. Yes, our code would be larger in size, but it would be many times more readable. And none of your colleagues will clutch their heads if they inherit such code :) Finally, I can recommend you the book. In the lecture we touched on the topic of code readability. The classic book “Clean Code” by Robert Martin is dedicated to her. 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 JavaRush.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION