Java - Operator Ternary Operator ?:

What is conditional operator?

Java conditional operator (ternary operator) takes three operands. It has the following form

boolean-expression ? true-expression : false-expression

If the boolean-expression evaluates to true, it uses the true-expression; otherwise, it uses false-expression.

The following code assigns minNum the minimum of num1 and num2 using ternary operator.

int num1 = 50;
int num2 = 25;

// Assigns num2 to minNum, because num2 is less than num1
int minNum = (num1 < num2 ? num1 : num2);

Demo

public class Main {
  public static void main(String[] args) {
    int num1 = 50;
    int num2 = 25;

    // Assigns num2 to minNum, because num2 is less than num1
    int minNum = (num1 < num2 ? num1 : num2);
    System.out.println ("minNum = " + minNum);

  }/*from  w  w  w.j  a  va  2 s .c o m*/
}

Result

Related Topics

Exercise