3.7 Conditional Operator

Java includes a special ternary(three-way) operator that can replace certain types of if-then-else statements. This operator is the ?. Here is an example of the way that the ? is used :

 max = number1 > number2 ? number1 : number2;

When Java evaluates this assignment expression, it first looks at the expression to the left of the question mark. If number1 is greater than number2, then the expression between the question mark and the colon is evaluated and used as the value of the entire ? expression. If number2 is greater, then the expression after the colon is evaluated and used for the value of the entire ? expression. The result produced by the ? operator is then assigned to max.

Here is a program that demonstrates the ? operator. It uses it to obtain the absolute value of a variable.

import java.util.Scanner;    // Needed for the Scanner class

/**
 * This program demonstrates the ? operator.
 */
public class TernaryDemo
{
   public static void main(String[] args)
   {
      int num;    // holds value of integer

      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);

      // Get an integer.
      System.out.print("Enter integer : ");
      num = console.nextInt();

      // Get absolute value of num
      num = (num < 0) ? -num : num;
      
      System.out.println("Absolute value is " + num);
   }
}          

Output 1:

Enter integer : -6
Absolute value is 6

Output 2:

Enter integer : 14
Absolute value is 14