Conditional Operators


Conditional operator consists of 3 operands and is used to evaluate Boolean expressions. This is also known as the ternary operator.

Note: It is also used as one liner replacement for if-then-else statement.


Syntax:

variable c = (expression) ? value if true : value if false

Example:

public class ConditionalOperator
{
    public static void main(String args[])
    {
        int x, y, z;
        x = 15;

        y = (x < 10) ? 10: 20;
        System.out.println(“Value of y is: “ + y);

        z = (x > 10) ? 10: 20;
        System.out.println(“Value of z is: “ + z);
    }
}

Output:

Value of y is: 20
Value of z is: 10