1. Technology

Conditional Operator

By

Definition:

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.
 

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.

Examples:

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

Glossary:

# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  1. About.com
  2. Technology
  3. Java
  4. Java Glossary
  5. C
  6. Conditional Operator Definition and Explanation

©2014 About.com. All rights reserved.