Classes/Objects  «Prev  Next»


Lesson 3 Logical operators
ObjectiveDescribe important points about the logical operators.

Java Logical operators

One of the exam objectives requires you to be able to analyze expressions involving the operators &, |, &&, and ||, and identify which operands are evaluated and the resulting value of the expression. The reason behind this objective is that the && and || operators exhibit a special " short-circuit" behavior when they are evaluated as part of a logical expression.
When an expression x && y is evaluated, the first operand x is evaluated. If x is false, then the evaluation of the second operand is skipped and the value of false is returned as the value of the expression.
When an expression x || y is evaluated, if x is true then the evaluation of the second operand is skipped and the value of true is returned as the value of the expression.
To see an example of the &, |, &&, and || operators in action, compile and run this ShortCircuit program.
The ternary operator also exhibits short-circuit behavior. If the first operand evaluates to true, the evaluation of the third operand is skipped. Similarly, if the first operand is false, the evaluation of the second operand is skipped. The ShortCircuit2 program provides an example of the short-circuit[1] behavior of the ternary operator.

Table 4.3 Operator Types and the relevant operators

Operator Types and the relevant operators
Operator Types and the relevant operators

Not all operators can be used with all types of operands. For example, you can determine whether a number is greater than another number, but you cannot determine whether true is greater than false or a number is greater than true. Take note of this as you learn the usage of all the operators on the OCA Java SE 7 Programmer I exam.

Logical Operators - Exercise

Click the Exercise link below to practice analyzing code using operators.
Logical Operators - Exercise

[1]Short-circuit: A boolean operation in which one operand determines the result of the operation.