Conditional expression

  • Conditional expression:

    • Conditional expression = an expression that returns a value based on a condition

  • Syntax of the conditional expression in Java:

       condition ? valueWhenTrue : valueWhenFalse 

    Example on how to use a conditional expression:

                                  Same effect:
    
       y = (x > 0) ? 1 : -1;      if ( x > 0 )
                                     y = 1;
                                  else
                                     y = -1;

A common usage of the conditional expression

  • The conditional expression is often used to:

    • Compute the maximum (or minimum) of 2 numbers

    Example:

    public class FindMaxMin 
    {
       public static void main(String[] args) 
       {
          Scanner input = new Scanner(System.in);
           
          double x, y, max, min;
          
          x = input.nextDouble();
          y = input.nextDouble();
    
          max = (x > y) ? x : y; 
          min = (x < y) ? x : y;
       }
    }  

DEMO: demo/03-selections/09-cond-expr/FindMaxMin.java