Java/J2EE and SOA (325 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (324 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What is Ternary Operator in Java and how can you use it?

Last updated on Nov 26,2019 840 Views
Aayushi Johari
A technophile who likes writing about different technologies and spreading knowledge. A technophile who likes writing about different technologies and spreading knowledge.
23 / 72 Blog from Java Core Concepts

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Conditional statements play an important role in the realm of programming. Doesn’t matter if the program is simple or complex, there is a high probability that the program contains conditional statements. There are times when we need to use them extensively but it becomes tedious to type the same thing again and again. To overcome this problem, we use a ternary operator which can be considered as the shorthand technique of if-else statements. In this java ternary operator post, we will understand all the essential concepts related to this operator and its usage.

Let’s get started. :-)

What is Ternary Operator in Java?

Ternary operator helps in converting several lines of code to a single line of code which makes it the best choice when small conditional operations are to be done several times.

Example

if (BooleanValue) {
   Greetings = "Hello!";
}
else {
   Greetings = "Bye!";
}

The above statement involves 6 lines and writing them, again and again, is a tedious task. Extensive use of if-else statement may create confusion of ‘{}’ in the code. To avoid this we use the ternary operator to simplify the code and minimize the chances of confusion.

Example-

Greetings = (BooleanValue) ? "Hello!" : "Bye!";

The above expression involves 1 line. Hence, if we have to write conditions, again and again, we can use the ternary operator for the purpose of simplification. 

In the next section of this post, we will go through all the components of the ternary operator in Java.

Working: How can you use Java Ternary Operator?

If you’re using the ternary operator for the first time it might look overwhelming. So, let’s break all the components that are present when we are using a ternary operator.

Greetings = (BooleanValue) ? "Hello!" : "Bye!";

From the above statement, we can see there is a total of 3 components of the ternary operator that we will go through one by one.

BooleanValue– It is a variable whose value is a boolean value that means it is either true or false. It is not necessary that it should be a variable, it can be an expression whose value after evaluation should be true or false. You can consider it similar to the condition that we mention while using if statement.

“Hello”- Just after ‘?’,‘Hello’ is placed. It basically means that if the value of ‘BoleanValue’ variable is ‘true’, ‘Hello!’ will be assigned to the ‘Greetings’ variable if the value of  ‘BoleanValue’ variable is ‘false’, ‘bye!’ will be assigned to the ‘Greetings’ variable.

Syntax:

Variablename = (Condition) ? the value assigned if 'true' is returned: the value assigned if 'true' is returned;

Java Ternary operators Examples

At this point, we know how to use the ternary operator. Now, let’s go through some examples which will provide us insights of different use cases and it’s limitations.

Let’s start with a classic example which is used most of the times while understanding the concept of conditional statements.

public class Ternaryy {
   public static void main(String[] args) {
       int Raining = 1;
       String Whether;

       Whether = (Raining == 1) ? "don't forget your umbrella" : "it's a sunny day";
       System.out.println(" Today " + Whether);
   }
}

Output- Today don’t forget your umbrella

Now, let’s see one more example:

public class Ternaryy {
   public static void main(String[] args) {
       String Toss = "Heads";
       String Result;

       Result = (Toss == "Heads") ? "You won the toss" : "Sorry, better luck nex time";
       System.out.println(Result);
   }
}

Output- You won the toss

The important points to remember while using the ternary operator are:

  • After understanding the working principle of the ternary operator, you might think of making it your prime choice when dealing with conditions but the catch here is that as the conditions start getting complex the code becomes less readable, which is not a good practice while programming. It can always be used when the expressions are short and simple.

  • The value returned after the evaluation of ternary operator should be stored in a variable of type same as that of the returned value. Else you will face an error and such errors are small, hence hard to find.

Chained Operations

Chained operations are also known as nested operations. They are similar to the nested if-else statements but with fewer lines of code.

public class Ternaryy {
   public static void main(String[] args) {

       String coffeeOrder = "Piccolo Latte";
       if (coffeeOrder == "Espresso" ) {
           System.out.println("would you like whipped cream on the top");
       } else if (coffeeOrder == "Piccolo Latte") {
           System.out.println("25ml or 30ml");
       } else if (coffeeOrder == "Short Macchiato") {
           System.out.println("Short or long");
       } else {
           System.out.println("Hello, we were unable to process your order");

       }
   }
}

Output-

25ml or 30ml

The above operation was simple enough but time-consuming. Let’s use the ternary operator to simplify our job.

public class Ternaryy {
   public static void main(String[] args) {

       String coffeeOrder = "Piccolo Latte";
        String FinalOrder = (coffeeOrder == "Espresso") ? " would you like whipped cream on the top" : (coffeeOrder == "Piccolo Latte") ? "25ml or 30ml" : (coffeeOrder == "Macchiato") ? "Short or long" : "Hello, we were unable to process your order";
       System.out.println(FinalOrder);
   }
}

The difference is crystal clear. Our second solution fulfills the purpose in fewer lines of code. It’s your choice, choose wisely according to the situation while selecting between if-else and ternary operator.

This is the end of the Ternary operator in Java article. I hope you guys are clear about each and every aspect that I have discussed above. 

Now that you have understood basics of Java, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Ternary operator in Java” blog and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.