header

Logical Expressions

A logical expression is an expression that evaluates to true or false.

Relational Operators and Relational Expressions

A relational operator compares two elements of the same primitive data type. A relational expression consists of two operands and a relational operator.

Relational Operator Typical Expression Result
> op1 > op2 true if op1 is greater than op2; false otherwise
>= op1 >= op2 true if op1 is greater than or equal to op2; false otherwise
< op1 < op2 true if op1 is less than op2; false otherwise
<= op1 <= op2 true if op1 is less than or equal to op2; false otherwise
== op1 == op2 true if op1 equals op2; false otherwise
!= op1 != op2 true if op1 is not equal to op2; false otherwise

Logical Operators

A logical operator requires logical operands and yields a logical result. There is one unary logical operator and two binary operators:

Name Logical Operator Example Result
NOT ! ! op true if and only if op is false
AND && op1 && op2 true if  and only if op1 and op2 are both true
OR || op1 || op2 false if and only if op1 and op2 are both false

Short-circuit Evaluation

Evaluation of && and || stops as soon as the result is known. That is, the value of op2 is evaluated only if it is necessary. Short-circuit evaluation results in faster programs by skipping unnecessary evaluations.

For the logical AND operation(&&), if op1 is false then the result will be false no matter what the value of op2 is. Consequently, op2 needs to be evaluated only if op1 is true.

For the logical OR operation (||), if op1 is true then the result will be true no matter what the value of op2 is. Consequently, op2 needs to be evaluated only if op1 is false.