Friday, November 22, 2019
Conditional Operator Definition and Explanation
Conditional Operator Definition and Explanation Conditional operators are used to evaluate a condition thats 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(Its divisible by two and four!); } else { Ã Ã System.out.println(Its 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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.