Conditional Operator ( ? : ) operator in Java



The trend of brevity was started by C programming language and Java inherits most of its virtues from C. The conditional ? : operator can create a very small code of what an if else statement would take.

To understand the conditional operator using ? : consider the following code written with if else. The code computes the minima of two numbers x and y.

  1. if (x < y) {
  2. min = x;
  3. }
  4. else {
  5. min = y ;
  6. }


These six lines of codes can be replaced with a single line of code.

min = (x < y ) ? x : y;

(x < y ) ? x : y; is an expression which returns one of two values, x or y. The condition, (x < y), is tested. If it is true the first value, x, is returned. If it is false, the second value, y, is returned. Whichever value is returned is dependent on the conditional test, x
The conditional ? : operator is called ternary operator and its general syntax olooks like

result = testCondition ? value1 : value2

If testCondition is true, result is assigned value1; otherwise, result is assigned value2.

Here is the complete Java example that prints the min of three numbers using ternary conditional statement.
  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   understanding ternary operator ? :
  4. This code will find min of three numbers
  5.   */
  6.  
  7. class ternary1{
  8. public static void main (String args[]) {
  9. int x = 21;
  10. int y = 24;
  11. int z = 18;
  12. int min;
  13.  
  14. min = (x < y ) ? x : y ;
  15. min = (min < z ) ? min : z ;
  16. System.out.println("Minimum of three numbers is "+ min);
  17. }
  18.  
  19. }


If you compile and run, you get the following output


Minimum of three numbers is 18