English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java ternary operator

In this article, you will learn how to change the control flow of a program using conditional or ternary operators.

Before learning about the ternary operator, you need to understandJava if ... else statementsThe ternary operator can be used to replace simple if...else statements. For example,

You can replace the following code

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

Is equivalent to:

number = (expression) ? expressionTrue : expressinFalse;

Why is the ternary operator named?Because it uses3number of operands.

Here, expression is a boolean expression with a result of true or false. If it is true, expressionTrue is evaluated and assigned to the variable number. If it is false, expressionFalse is evaluated and assigned to the 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 number" : "Non-positive number";
      System.out.println(number + " is " + result);
   }
}

When running the program, the output is:

-5.5 Is a non-positive number

When to use the ternary operator?

You can use the ternary operator to replace multi-line code with a single line code. It makes your code more readable. However, do not overuse the ternary operator. 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;
}

Is equivalent to:

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

In this case, the use of the ternary operator makes the code difficult to understand.

Use the ternary operator only when the result statement is brief. This will make your code clear and easy to understand.