Conditional Operators

Programming language
Getty Images/ermingut

Conditional operators are used to evaluate a condition that's applied to one or two boolean expressions. The result of the evaluation is either true or false.

There are three conditional operators:

 &&   the logical AND operator.
||   the logical OR operator.
?:   the ternary operator.

Conditional Operators

The logical AND and logical OR operators both take two operands. Each operand is a boolean expression (i.e., it evaluates to either true or false). The logical AND condition returns true if both operands are true, otherwise, it returns false. The logical OR condition returns false if both operands are false, otherwise, it returns true.

Both the logical AND and logical OR operators apply a short circuit method of evaluation. In other words, if the first operand determines the overall value for the condition, then the second operand is not evaluated. For example, if the logical OR operator evaluates its first operand to be true, it does not need to evaluate the second one because it already knows the logical OR condition has to be true. Similarly, if the logical AND operator evaluates its first operand to be false, it can skip the second operand because it already knows the logical AND condition will be false.

The ternary operator takes three operands. The first is a boolean expression; the second and third are values. If the boolean expression is true, the ternary operator returns the value of the second operand, otherwise, it returns the value of the third operand.

An Example of Conditional Operators

To test if a number is divisible by two and four:

 int number = 16;
if (number % 2 == 0 && number % 4 == 0)
{
  System.out.println("It's divisible by two and four!");
}
else
{
  System.out.println("It's not divisible by two and four!");
}

The conditional operator "&&" first evaluates whether its first operand (i.e., number % 2 == 0) is true and then evaluates whether its second operand (i.e., number % 4 == 0) is true. As both are true, the logical AND condition is true.

Format
mla apa chicago
Your Citation
Leahy, Paul. "Conditional Operators." ThoughtCo, Feb. 16, 2021, thoughtco.com/conditional-operator-2034056. Leahy, Paul. (2021, February 16). Conditional Operators. Retrieved from https://www.thoughtco.com/conditional-operator-2034056 Leahy, Paul. "Conditional Operators." ThoughtCo. https://www.thoughtco.com/conditional-operator-2034056 (accessed March 28, 2024).