Skip Top Navigation Bar

Using Logic Operators

Logic Operators

Logic operators are used to combine boolean expressions. The most common logic operators 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

Let's try it in the Java Playground.

Negating a Boolean Expressions with a Relational Operator

The expression !(3 < 5) is equivalent to 3 >= 5. When the not (!) operator is used on an expression with a relationship operator, the equivalent expression uses the opposite relational operator. The opposite of less than is greater than or equal to. The opposite of greater than is less than or equal to.

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

Let's try it in the Java Playground.

Resources

Practice: Using Logic Operators

Next Learn Tutorial

Learn: Applying DeMorgan's Law