Skip Top Navigation Bar

Using Logic Operators

Logic Operators

Logic operators are used to combine boolean expressions. The most common ones are listed in the table below.

Operator Name Description Example
! not evaluates to true if the boolean expression is false and false if the boolean expression is true.
  • !(3 > 5) evaluates to true since 3 > 5 evaluates to false.
  • !(5 > 3) evaluates to false since 5 > 3 evaluates to true.
&& and evaluates to true if both boolean expressions evalute to true and false if one or both boolean expressions evaluate to false.
  • true && true evaluates to true.
  • true && false evaluates to false.
  • false && true evaluates to false.
  • false && false evaluates to false.
|| or evaluates to true if at least one of the boolean expressions evalute to true and false if both boolean expressions evaluate to false.
  • true || true evaluates to true.
  • true || false evaluates to true.
  • false || true evaluates to true.
  • false && false evaluates to false.

Truth Tables

Boolean expressions can be evaluated by using truth tables. A truth table lists all the possible values and the associated output.

Not (!) Operator

When evaluating !a, there are two possible combinations:

Truth Table for ! Expression.

And (&&) Operator

When evaluating a && b, there are four possible combinations:

Truth Table for && Expression.

Or (||) Operator

When evaluating a || b, there are four possible combinations:

Truth Table for || Expression.

Your Turn

Try these out in the Java Playground.

DeMorgan's Law

DeMorgan's Law applies in situations when a not (!) operator is being used in combination with either the and (&&) or the or (||) operators.

Truth Table to Prove DeMorgan's Law

Rule Description Example
!(value1 && value2) evaluates to !value1 || !value2 where value1 and value2 are boolean expressions. !((5 > 7) && (3 !=0)) is equivalent to (5 <= 7) || (3 == 0)
!(value1 || value2) evaluates to !value1 && !value2 where value1 and value2 are boolean expressions. !((val + 5 <= 0) || (5 == 5)) is equivalent to (val + 5 > 0) && (5 != 5)

Short-Circuit Evaluation

If the value of a boolean expression that involves a logic operator can be determined based on only the first boolean expression, the second boolean expression is not evaluated.

And (&&) Operator Short-Circuit

If the first expression evaluates to false, the expression with the && operator evaluates to false.

This example is a popular use of short-circuit for &&. If the value of numGrades is 0, we would get a divide by 0 error when attempting totalGrades / numGrades. Checking that numGrades is not 0 before performing division can prevent this error. Try it out! Run the code as is, and then change the value of numGrades to 0.

Your Turn

Resources

Practice: Using Logic Operators