Conditional (Ternary) Operator in Java Example

The character pair ? : is called ternary operator in Java because it acts on three variables.

This operator is also known as conditional operator in Java. It is used to make a conditional expression.

It has the following syntax in java:


variable = exp1 ? exp2 : exp3;
       where exp1, exp2, and exp3 are expressions.

Operator ? : works as follows:

First of all, the expression exp1 is evaluated. If it is true, the expression exp2 will be evaluated and the value of exp2 will store in the variable. If exp1 is false, exp3 will be evaluated and its value will store in the variable.

Consider the following example:

int a = 40;
int b = 30;
int x = (a > b) ? a : b;

Here, first (a > b) is evaluated. If it is true, the value of a is stored in the variable x. If it is false, the value of b is stored in the variable x.

Here, (a > b) is true because the value of a is greater than the value of b. Therefore, the value of a will assign in the variable x. That is, x = 40.

In the above example, we have used 3 variables a, b, and x. That’s why it is called ternary operator in java. This example can also be achieved by using the if-else statement as follows:

if(a > b) 
  x = a;
else {
       x = b;

Let’s create a program where we will find out the greatest number between the two numbers.

Program source code 1:

package operatorPrograms; 
public class Test 
public static void main(String[] args) 
 int x = 20; 
 int y = 10; 
 int z = (x > y) ? x : y; 
System.out.println("Greatest number: " +z); 
           Greatest number: 20

Hope that this tutorial has covered all important points related to the conditional (ternary) operator in java with example program. I hope that you will have understood the basic concept of ternary operator and enjoyed programming.
Thanks for reading!!!
Next ⇒ Bitwise Operator in Java⇐ PrevNext ⇒

Leave a Comment