Java Ternary Operator

The Java ternary operator allows you to build a single-line if statement. True or false can be the result of a ternary operator. Whether the statement evaluates to true or false, it returns a certain result.

Operators are the fundamental building blocks of all programming languages. Java, too, has a variety of operators that can be used to accomplish various calculations and functions, whether logical, arithmetic, relational or otherwise. They are categorized according to the features they offer. Here are several examples:

  • Arithmetic Operators
  • Unary Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators

Java Ternary Operator with examples

This article covers everything there is to know about Arithmetic Operators.

There are three parts to the definition of ternary. Three operands make up the ternary operator (?:). Boolean expressions are evaluated with it. The operator chooses which value to assign to the variable. It’s the only conditional operator that takes three arguments. It can take the place of an if-else expression. It simplifies, simplifies, and simplifies the code. A ternary operator cannot be used to replace any code that uses an if-else statement.

Operator Ternary

The only conditional operator in Java that takes three operands is the ternary operator. It’s a one-liner substitute for the if-then-else statement commonly used in Java. We can use the ternary operator instead of if-else conditions or nested ternary operators to swap conditions.

Although the conditional operator follows the same algorithm as the if-else statement, it takes up less space and aids in the shortest possible writing of if-else statements.

The ternary operator syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>resultant_variable = First_Expression ? Second_Expression: Third_Expression</pre>
</div>

Its expression works the same way as the if-else statement in that Second_Expression is executed if First_Expression is true and Third_Expression is executed if First_Expression is false.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>if(First_Expression)
{
    resultant_variable = Second_Expression;
}
else
{
    resultant_variable = Third_Expression;
}</pre>
</div>

Below is a simple demonstration of Java’s ternary operator.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>varNumOne = 25;
varNumTwo = 35;

final_result=(varNumOne>varNumTwo) ? (varNumOne+varNumTwo):(varNumOne-varNumTwo)

Since num1<varNumTwo,

// performing the second operation
final_result = varNumOne-varNumTwo = -10</pre>
</div>

When should the Ternary Operator be used?

The ternary operator in Java can be used to replace some if…else sentences. For instance, the following code can be changed as follows.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class codeIfElse {

  public static void main(String[] args) {
    
    // creation of the variable
    int gradeVar = 68;

    if( gradeVar > 0) {
      System.out.println("Congratulations. You have a Positive Trend");
    }
    else {
      System.out.println("Sorry. You have a Negative Trend");
    }
  }
}</pre>
</div>

with

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class codeTernary {

  public static void main(String[] args) {
    
    // creation of the variable
    int gradeVar = 68;

    String resultantFeedback = ( gradeVar > 0) ? "Congratulations. You have a Positive Trend" : "Sorry. You have a Negative Trend";
    System.out.println(resultantFeedback);
  }
}
</pre>
</div>

Both programs give the same result in this case. On the other hand, the ternary operator makes our code more legible and tidy. Note that the ternary operator should only be used if the resulting sentence is brief.

Nesting the Ternary Operators in Java

One ternary operator can also be used inside another ternary operator. In Java, it’s known as the nested ternary operator. Here’s a program that uses the nested ternary operator to discover the largest of three numbers.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class codeNestedTernary {

  public static void main(String[] args) {
    
    //  Here's the declaration of variables
    int numVarOne = 7, numVarTwo = 13, numVarThree = -8;

    //To find the greatest number, use a nested ternary operator.
    int varLargestNum = ( numVarOne >= numVarTwo) ? (( numVarOne >= numVarThree) ? numVarOne : numVarThree) : (( numVarTwo >= numVarThree) ? numVarTwo : numVarThree);
    
System.out.println(" The greatest number among the three is: " + varLargestNum);
  }
}</pre>
</div>

Notice how the ternary operator is used in the preceding example.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre> ( numVarOne >= numVarTwo) ? (( numVarOne >= numVarThree) ? numVarOne : numVarThree) : (( numVarTwo >= numVarThree) ? numVarTwo : numVarThree);</pre>
</div>

Here,

( numVarOne >= numVarTwo) is the initial test condition, determining whether numVarOne is bigger than numVarTwo. In case the beginning condition is correct, the second test condition ( numVarOne >= numVarThree) is executed. Further, upon the beginning condition being false, the third test condition (numVarTwo >= numVarThree) is run. Note that nested ternary operators are not recommended. This is because it complicates our coding.

Evaluation of Expression

Only one of the right-hand side expressions, expression1 or expression2, is evaluated at runtime when employing a Java ternary construct. A simple JUnit test case may be used to verify this:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>@Test
public void codeWhenConditionIsTrue() {
    int varExp1 = 0, varExp2 = 0;
    int ternaryResult = 23 > 21 ? ++ varExp1 : ++varExp2;
    
    assertThat(varExp1).isEqualTo(1);
    assertThat(varExp2).isEqualTo(0);
    assertThat(ternaryResult).isEqualTo(1);
}</pre>
</div>

Because our boolean statement 23 > 21 is always true, the value of varExp2 stayed unchanged. Consider what occurs in the case of a false condition:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>@Test
public void codeWhenConditionIsFalse() {
    int varExp1 = 0, varExp2 = 0;
    int result = 19 > 21 ? ++ varExp1 : ++varExp2;

    assertThat(varExp1).isEqualTo(0);
    assertThat(varExp2).isEqualTo(1);
    assertThat(result).isEqualTo(1);
}</pre>
</div>

The value of varExp1 was not changed, but the value of varExp2 was raised by one.

Null Check using Ternary Operator

Before attempting to invoke an object’s method, you can use the Java ternary operator as a shorthand for null checks. Consider the following scenario:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>String varResult = object != null ? object.getValue() : null;

This code is the very equivalent of the one above only that the prior is much shorter than this one:

String varResult = null;
if(object != null) {
    varResult = object.getValue();
}</pre>
</div>

Both of these code examples, as you can see, avoid calling objects. If the object reference is null, object.getValue() is called, although the first code sample is a little shorter and more elegant.

Max Function using Ternary Operator

Using a Java ternary operator, you may obtain the same capability as the Java Math max() function. Here’s an example of utilizing a Java ternary operator to achieve the Math.max() functionality:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>int varNumOne = 23;
int varNumTwo = 38;

int varMaxResult = varNumOne >= varNumTwo ? varNumOne : varNumTwo;</pre>
</div>

Take note of how the ternary operator conditions check whether varNumOne is greater than or equal to varNumTwo. The ternary operator returns the value varNumOne if it is true. Otherwise, the varNumTwo value is returned.

Min Function using Ternary Operator

To get the same result as the Java Math min() function, utilize the Java ternary operator. Here’s an example of utilizing a Java ternary operator to achieve the Math.min() functionality:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>int varNumOne = 23;
int varNumTwo = 38;

int varMaxResult = varNumOne <= varNumTwo ? varNumOne : varNumTwo;</pre>
</div>

Notice how the ternary operator conditions check to see if varNumOne is less than or equal to varNumTwo. The ternary operator returns the value varNumOne if it is true. Otherwise, the varNumTwo value is returned.

Abs Function using Ternary Operator

The Abs function effect is achievable through Java’s ternary operator as with the Java Math abs() method. Here’s an example of utilizing a Java ternary operator to achieve the Math.abs() functionality:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>int varNumOne = 23;

int varAbsoluteResult = varNumOne >= 0? varNumOne : -varNumOne;</pre>
</div>

Take note of how the ternary operator examines if varNumOne is greater than or equal to 0.

The ternary operator returns the value varNumOne if it is true. Otherwise, it returns -varNumOne, which negates a negative value and makes it positive.

Example: Nesting Ternary Operator

It’s feasible to nest our ternary operator to any number of levels we choose. In Java, this construct is valid:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>String ternaryResult = varNum > 38 ? "Number is greater than 38" :
  varNum > 8 ? "Number is greater than 8" : "Number is less than equal to 8";

We can use brackets () wherever appropriate to improve the readability of the above code:

String ternaryResult = varNum > 38 ? "Number is greater than 38"
  : ( varNum > 8 ? "Number is greater than 8" : "Number is less than equal to 8");</pre>
</div>

Please keep in mind that such deeply nested ternary structures are not advised in the actual world. This is due to the fact that it makes the code less legible and maintainable.

Example: Program for finding the largest among two numbers using Java’s ternary operator

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.io.*;

class CodeTernary {

	public static void main(String[] args)
	{

		// The declaration of  variables
		int varNumOne = 15, varNumTwo = 98, varNumMax;

		System.out.println("The First num is: " + varNumOne);
		System.out.println("The Second num is: " + varNumTwo);

		// Largest value between  varNumOne and  varNumTwo
		varNumMax = ( varNumOne > varNumTwo) ? varNumOne : varNumTwo;

		// Printing the largest number between the two
		System.out.println("Maximum is = " + varNumMax);
	}
}</pre>
</div>

Example: Code for illustrating Java’s ternary operator

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.io.*;

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

		// The declaration of variables
		int varNumOne = 18, varNumTwo = 65, varNumRes;

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

		// Executing the ternary operation in Java
		varNumRes = ( varNumOne > varNumTwo) ? ( varNumOne + varNumTwo) : ( varNumOne - varNumTwo);

		// Print the largest number
		System.out.println("The resultant values is = " + varNumRes);
	}
}</pre>
</div>

Example: Java’s Ternary Operator

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

class CodeTernary {

  public static void main(String[] args) {
    
    //solicit user for input
    Scanner codeInput = new Scanner(System.in);
    System.out.println("Please input your end of semester Score: ");

    double studentsScore = codeInput.nextDouble();

    // ternary operator  is responsible for checking if
    // studentsScore is higher than 70
    String resultScore = ( studentsScore > 70) ? "Pass. Promoted to Level II" : "Fail. Cannot be promoted to Level II";

    System.out.println("Your end of  year evaluation is" + resultScore );
    codeInput.close();
  }
}</pre>
</div>

Example: Ternary Operator demo in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class codeTernaryOperator  
{  

  public static void main(String args[])   
  {  
    int xVar, yVar;  
    xVar = 43;  
    yVar = (xVar == 1) ? 98: 108;  

    System.out.println("The Value of yVar is: " +  yVar);  

    yVar = (xVar == 43) ? 98: 108;  
    System.out.println("The Value of yVar is: " + yVar);  
  }  
}  </pre>
</div>

Example: Determine the Largest number using a Ternary Operator in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class codeLargestNumber  
{  
  public static void main(String args[])  
  {  
    int xVar=169;  
    int yVar=189;  
    int zVar=179;  

    int varLargestNum= (xVar > yVar) ? (xVar > zVar ? xVar : zVar) : (yVar > zVar ? yVar : zVar);  
    System.out.println("The greaterst numbers is:  "+varLargestNum);  
  }  
}  </pre>
</div>

Conclusion

With the help of examples, you have learned about the ternary operator and how to utilize it in Java in this tutorial. In some cases, a ternary operator can be used instead of an if…else statement in Java. We also used an example to show the Java if…else statement before diving into the ternary operator. In addition, the test condition is evaluated by a ternary operator, which then executes a block of code based on the outcome.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *