Automation QA Testing Course Content

Java Ternary Operator with Examples

This article explains all that one needs to know regarding the Ternary Operator

Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for if-then-else statement and used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators. Although it follows the same algorithm as of if-else statement, the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.







Syntax:
variable = Expression1 ? Expression2: Expression3
If operates similarly to that of the if-else statement as in Exression2 is executed if Expression1 is true else Expression3 is executed.
if(Expression1)
{
    variable = Expression2;
}
else
{
    variable = Expression3;
}
// Java program to find largest among two 
// numbers using ternary operator 

import java.io.*; 

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

  // variable declaration 
  int n1 = 5, n2 = 10, max; 

  System.out.println("First num: " + n1); 
  System.out.println("Second num: " + n2); 

  // Largest among n1 and n2 
  max = (n1 > n2) ? n1 : n2; 

  // Print the largest number 
  System.out.println("Maximum is = " + max); 
 } 
} 
Example 2:

// Java code to illustrate ternary operator 

import java.io.*; 

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

// variable declaration 
int n1 = 5, n2 = 10, res; 

System.out.println("First num: " + n1); 
System.out.println("Second num: " + n2); 

// Performing ternary operation 
res = (n1 > n2) ? (n1 + n2) : (n1 - n2); 

// Print the largest number 
System.out.println("Result = " + res); 

Example: Java Ternary Operator

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

      Double number = -5.5;
      String result;
      
      result = (number > 0.0) ? "positive" : "not positive";
      System.out.println(number + " is " + result);
   }
}
When you run the program, the output will be:
-5.5 is not positive

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.