1
0

Conditional Operator in Java

The conditional operator is ? : (also called Ternary Operator). This can be thought of as shorthand for an if-else statement (discussed in this tutorial’s Control Flow Statements section). This operator is known as the ternary operator because it uses three operands. In the following example, this operator should be read as: “If exp1 is true, then assign the value of exp2 to var. Otherwise, assign the value of exp3 to var.”

Syntax: var = exp1 ? exp2 : exp3;

Where exp1 is a logical expression that results in a true or false value, exp2 and exp3 are expressions that result in numerical values. The first exp1 is evaluated and if it results in a true value that the result of exp2 is assigned to var otherwise if exp1 results in a false value the result of exp3 is assigned to var.

Program to test the conditional operator

class ConditionalDemo2
{
    public static void main(String[] args)
    {
        int value1 = 1;
        int value2 = 2;
        int result;
        boolean someCondition = true;
        result = someCondition ? value1: value2;
        System.out.println(result);
    }
}

Because the value of variable someCondition is true, this program prints “1” to the screen. Use of the ?: operator instead of an if-else statement makes your code more readable and compact.

Leave a Reply