Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

10 Examples Of Ternary Operator In Java

Hello guys, if you are wondering how to use ternary operator in Java then you have come to the right place. Ternary operator is a great operator and you can use ternary operator to replace a simple if-else statement. Since ternary operator allows you to write code in one line, its much more succinct and readable and that's what many Java developer love it, including me. In the last article, I shared 10 example of XOR bitwise operator in Java and in this article, I am going to share 10 example of ternary operator in Java so that you not only know what is ternary operator but also you can use it effectively to write better Java code. But, before we get to the 10 best examples that will teach you everything there is to know about ternary operators in Java, let me tell you a little bit more about what it all really is.

The first thing you need to understand is that operators are actually the most basic building blocks of a programming language. In a programming language, operators allow you to perform many calculations and functions like arithmetic, logic, and rationale. Operators are classified according to their functionality. 

The ternary operator in Java is a conditional operator that takes three operands. It can act as a replacement for the if-then-else statement and can also be used a lot in Java programming. You can use the ternary operator in place of if-else conditions or you can also switch conditions with the help of nested ternary operators. 


10 Examples Of Ternary Operator In Java

Here we have compiled a list of 10 examples of the ternary operator in Java. Keep reading to find out more. 

1. Ternary Operator as an alternative to If-Else

This example will show you how to write simple code in Java using a ternary operator. In this program, resultValue is assigned a value according to the evaluation of that particular expression. You can replace the complicated if-else statement with a single line. 

You may think that this is not really a significant change in terms of programming. But in many cases, using an if-else statement can become really complicated. You can also significantly reduce the lines of code in your program by using the ternary operator. 

public class TernaryOperatorDemo2{
  public static void main(String[] args) {
        int x = 5;
        int y = 10;
String resultValue=(x>=y)?"x is greater than or maybe equal to y":"x is less than y";
       System.out.println(resultValue); //o/p is x is less than y
  }
}

10 Examples Of Ternary Operator In Java


2. Using The Ternary Operator as an alternative to if-else-if

Another important thing to note is that you can also use the ternary operator as an alternative to if-else-if. For example, look at the following program. 

public class TernaryOperatorDemo3{
  public static void main(String[] args) {
       int percentage=70;
        
       if(percentage>=60){  
           System.out.println("A grade");  
       }else if(percentage>=40){  
           System.out.println("B grade");  
       }else {  
           System.out.println("Not Eligible");  
       }
  }
}

In this program, the if-else-if statement is useful for printing the final result by comparing the percentage. You can make this code simpler and easy to read by using the ternary operator in place of if-else-if. 

public class TernaryOperatorDemo4{
 public static void main(String[] args) {
   int percentage=70;  
         
   String resultValue = (percentage>=60)? 
   "A grade":((percentage>=40)?"B grade":"Not    Eligible");
        System.out.println(resultValue); 
   }
}

This program will also print the same result as the earlier program with fewer lines of code. 



3. Using the ternary operator as an alternative to switch-case

You can also use the ternary operator as a replacement for switch-case. In this example, you can see that the switch-case statement is used to calculate the value that is to be assigned to the string variable. In this case, the string variable is a color value that is assigned based on the color code integer. 

public class TernaryOperatorDemo5{
  public static void main(String[] args) {
        int colorCode = 101;
        String color = null;
        switch(colorCode) {
          case 100 :
            color = "Yellow"; 
            break;
          case 101 :
            color = "Green";
            break;
          case 102 : 
            color = "Red";
            break;
           default :
            color = "Invalid";       
        }
       System.out.println("Color --->"+color);
  }
}


You can simply replace the switch-case statement with a ternary operator. The ternary operator will help you make your code simpler. 

public class TernaryOperatorDemo6{
 public static void main(String[] args) {
   int colorCode = 101;
   String color = null;   color=(colorCode==100)? 
   "Yellow":((colorCode==101)?"Green":((colorCode==102)?"Red":"Invalid"));
    System.out.println("Color --->"+color);   }
}


You can see that the switch-case statement has been replaced with a single line of code. 


4. Defining a ternary operator in Java

You can simply define a ternary operator in Java with the following syntax:

resultValue = testConditionStatement ? value1 : value2;

The resultValue will get a value of either value1 or value2 according to the testConditionStatement value. This will either be true or false. 

5. Writing a ternary condition in Java

You already know that a ternary operator in Java uses 3 operands. The testConditionStatement will return a boolean value. You can see the following example to get a better understanding of ternary operators in Java. 




resultValue = testConditionStatement ? value1 : value2;

String result = (-2>2) ? yes : no;

6. Nested Ternary Operators

You can also use one ternary operator inside another ternary operator. This is known as a nested ternary operator in Java. For a better understanding, you can see the following program which aims to find the largest of 3 numbers using a nested ternary operator. 

class Main {
  public static void main(String[] args) {
    
    // create a variable
    int n1 = 2, n2 = 9, n3 = -11;

    // nested ternary operator
    // to find the largest number
    int largest = (n1 >= n2) ? ((n1 >= n3) ? n1 : n3) : ((n2 >= n3) ? n2 : n3);
    System.out.println("Largest Number: " + largest);
  }
}

In this example, the resulting output will be like this:

Largest Number: 9

7. Replacing a simple if-else statement with a ternary operator

As you already know, ternary operators can be used in Java to replace certain types of if-else statements. 

class Main {
  public static void main(String[] args) {
    
    // create a variable 
    int number = 24;

    if(number > 0) {
      System.out.println("Positive Number");
    }
    else {
      System.out.println("Negative Number");
    }
  }
}


You can replace the above code, which seems unnecessarily complicated. 

class Main {
  public static void main(String[] args) {
    
    // create a variable 
    int number = 24;

    String result = (number > 0) ? "Positive Number" : "Negative Number";
    System.out.println(result);
  }
}

As you can see, this looks much more neat and readable.


8. Evaluating An Expression with a ternary operator

public void whenConditionIsTrue_thenOnlyFirstExpressionIsEvaluated() {
    int exp1 = 0, exp2 = 0;
    int result = 12 > 10 ? ++exp1 : ++exp2;
    
    assertThat(exp1).isEqualTo(1);
    assertThat(exp2).isEqualTo(0);
    assertThat(result).isEqualTo(1);
}

In this case, the boolean expression will always evaluate as true. 

9. Nesting a ternary operator

String msg = num > 10 ? "Number is greater than 10" : 
  num > 5 ? "Number is greater than 5" : "Number is less than equal to 5";

You can simply nest a ternary operator inside another ternary operator. 


10. Nested Ternary Operator

String msg = num > 10 ? "Number is greater than 10" 
  : (num > 5 ? "Number is greater than 5" : "Number is less than equal to 5");


That's all about what is ternary operator in Java and how to use it. To be honest, even though I have used ternary operator every day, I didn't know many of the tricks like nesting ternary operator until I decided to write this article. There is so much to learn in Java but learning ternary operator is definitely worth it as it allows you to write cleaner and more readable code because you can put condition and both value in same line. 



Some Programming problems based on the bitwise operator :
  • How to swap two numbers without using a temp variable? (solution)
  • How to solve the Producer-Consumer Problem in Java. (solution)
  • How to find if the number is even or odd? (solution)
  • How to find the Fibonacci sequence up to a given number? (solution)
  • Write a method to remove duplicates from ArrayList in Java? (Solution)
  • How to find Greatest Common Divisor of two numbers in Java? (solution)
  • 10 Courses to Crack any Programming interview (courses)
  • How to check if LinkedList contains any cycle in Java? (solution)
  • How to check if a number is Armstrong's number or not? (solution)
  • How do find the largest and smallest number in an array? (solution)
  • How to add two numbers without using the + operator in Java? (solution)
  • How to find prime factors of an integer in Java? (solution)
  • How to check if an integer is a power of two in Java? (solution)
  • How to find the first non-repeated characters from String in Java? (program)

Thanks for reading this article so far. If you liked this list of 10 examples of the ternary operator in Java, feel free to share it with your friends and family. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.