CodeGym/Java Blog/Statements in Java/Java Ternary operator
Author
Vasyl Malik
Senior Java Developer at CodeGym

Java Ternary operator

Published in the Statements in Java group
members
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). The 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 Martin'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.
Comments (25)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Jesú
Level 14 , Madrid, Spain
14 October 2023, 15:03
You can also do this:

   System.out.println((person.getAge() > 18) ? "Everything is in order. Come in!" : "This film is not suitable for your age!");
Ricardo
Level 10
11 July 2021, 15:58
Technically speaking, the
condition ? if_true : if_false
operator is called conditional operator. People call it ternary operator because it is the only three arguments operator at this moment in Java. But other languages or Java in the future could be added other three arguments operators.
Vlad
Level 29 , Khon Kaen, Thailand
15 June 2021, 13:35
typo close to the end of the article "Finally, I can recommend a good for you." should be "Finally, I can recommend a good book for you."
Daniela
Level 23 , Bucuresti, Romania
16 April 2021, 14:13
Ternary operator is super cool! :D
Kamil
Level 7 , The Earth, Milky Way
5 November 2020, 11:21
There is a mistake in author's of the book last name.
amj
Level 7 , Imphal , India
12 August 2020, 04:08
i have heard about ternary operator in school from last 3 years ago but i didn't understand it. Now from code gym i get it.
Java Learner
Level 11 , Herlev, Denmark
27 June 2020, 08:42
Great article, really helps to learn the ternary operator. Basically ternary operator eliminated the if-else boiler plate code and write it in the compact way by making it more readable.
Brandon Leirer
Level 7 , Keller, United States
6 June 2020, 19:10
in the if-else statement, the code said >=18, but in the ternary it said >18 . Was this just a typo, or can the ternary not do >= ?
BlueJavaBanana
Level 37
19 June 2020, 16:12
The ternary statement can do anything that evaluates to true or false. So it could compare two strings and place the result into a variable like this: String result = ("hello".equals("hello")) ? "These Strings match!" : "These Strings do not match!"; Or if working with integers you could do this: Compare x and y and set a third integer to be the biggest of the two. int x = 10; int y = 17; int biggestInt = x > y ? x : y; System.out.println(biggestInt);
Peter Schrijver
Level 23 , Hilversum, Netherlands
25 May 2020, 08:58
For me code must be readable
mdkr
Level 6 , San Francisco, United States
16 January 2020, 20:26
you can download this book for free in this site web : site