Docsity

Boolean Logic: Operators, Short Circuit Evaluation, and De Morgan's Laws - Prof. Suzanne B, Study notes of Java Programming

Partial preview of the text

Download Boolean Logic: Operators, Short Circuit Evaluation, and De Morgan's Laws - Prof. Suzanne B and more Study notes Java Programming in PDF only on Docsity!

Boolean Variables

Boolean Values/Expressions

  • Review
  • “Exclusive or” vs. “Inclusive or”
  • De Morgan’s Laws
  • Short Circuit Evaluation
  • Logical Operator Precedence
  • Examples
    • TaxCalculator

Copyright 2006 by Pearson Education 2

Type boolean

boolean : A primitive type to represent logical values.  A boolean expression produces either true or false.  The s in if statements, for loops are boolean.

 Examples: boolean minor = (age < 21); boolean expensive = (iPhonePrice > 500.00); boolean iLoveCS = true; if (minor) { System.out.println("Can't purchase " + "alcohol!"); }  You can create boolean variables, pass boolean parameters, return boolean values from methods, ...

“Exclusive or” vs. “Inclusive or”

  • We generally use “exclusive or” when speaking: “I’ll do my homework or go to the party” means I’ll do one or the other, but not both.
  • Programming uses “inclusive or”. An expression is true if either or both conditions are true: 2 > 3 || 4 < 5 F || T = T 2 < 3 || 4 < 5 T || T = T (^4)

De Morgan’s Laws

! ( p && q) = !p || !q

! (x < y && y < z ) = !(x < y) || !(y < z)

= x >= y || y >= z

Short Circuit Evaluation

  • Short Circuit Evaluation – The property of the logical operators && and || that prevents the second operand from being evaluated if the overall result is obvious from the value of the first operand.
  • Examples:

2 > 3 && 4 < 5 F &&? = F

2 < 3 || 4 > 5 T ||? = T (^7)

Logical Operator Precedence

Not! Highest Precedence

And &&

Or || Lowest Precedence

Example:

2 < 3 || 4 > 5 && 6 > 7

HINT: When in doubt, use parentheses!

Method Example

if (x < y) { OK

return true;

else {

return false;

return x < y; COOLER!

Logical Operator Example

if (x < y) { BAD

if (y < z) {

if (x < y && y < z) { BETTER!

public static double calculateTax(boolean isMarried, int income) { double tax = 0; if (isMarried) { if (income <= 16000) { tax = .10 * income; } else if (income <= 64000) { }^ tax = 1600 + .15 * (income - 16000); else { tax = 8800 + .25 * (income - 64000); } } else { (^) if (income <= 8000) { }^ tax = .10 * income; else if (income <= 32000) { tax = 800 + .15 * (income - 8000); } else { }^ tax = 4400 + .25 * (income - 32000); } return tax; } NOTE: Class constants should be used instead of magic numbers!!!