Java Ternary Operator

In this article, you will learn to use conditional or ternary operator to alter control flow of the program.

Before you learn about ternary operator, you need to understand if...else statement in Java. Ternary operator can be used to replace if...else statement. For example,

You can replace the following code

if (expression) {
   number = 10;
}
else {
   number = -10;
}

with

number = (expression) ? expressionTrue : expressinFalse;

Why name ternary operator? Because it uses 3 operands.

Here, expression is a boolean expression which evaluates to either true or false. If it evaluates to true, expressionTrue is evaluated and assigned to variable number. If it evaluates to False, expressionFalse is evaluated and assigned to variable number.


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

When to use ternary operator?

You can replace multiple lines of code with a single line of code using ternary operator. It makes your code more readable. However, don't over do it. For example,

You can replace the following code

if (expression1) {
	result = 1;
} else if (expression2) {
	result = 2;
} else if (expression3) {
	result = 3;
} else {
	result = 0;
}

with

result = (expression1) ? 1 : (expression2) ? 2 : (expression3) ? 3 : 0;

The use of ternary operators made the code harder to understand in this case.

Use ternary operators only when the resulting statement is short. This will make you code concise and much more readable.