2.6 Comparing Boolean Expressions

8 阅读1分钟

1. Exam Points

  • Two Boolean expressions are equivalent if they have the same value in all cases.
  • De Morgan’s law:
    • !(a && b) is equivalent to !a || !b
    • !(a || b) is equivalent to !a && !b
  • Compare object references using == or !=.
  • Compare object references using the equals method.
  • Compare an object reference and null using == and !=
  • Note: Do not access members on a null object.

2. Knowledge Points

(1) Comparing Boolean Expressions

  • Two Boolean expressions are equivalent if they evaluate to the same value in all cases.
    • Example:
      • ! ( a && b ) is equivalent to !a || !b
      • !( x > y && x > z ) is equivalent to !(x > y) || !(x > z)
  • De Morgan’s law can be applied to Boolean expressions to create equivalent Boolean expressions.
  • Under De Morgan’s law:
    • !(a && b) is equivalent to !a || !b
    • !(a || b) is equivalent to !a && !b
    • !(a && b && c) = !a || !b || c
    • !(a || b || c) = !a && !b && c

(2) Compare Variables of Reference Types

  • Two different variables can hold references to the same object.
    • Example 1: d1 and d2 refer to different objects.
    Dog d1 = new Dog() ;
    Dog d2 = new Dog() ;
    
    • Example 2: d1 and d2 refer to the same object
    Dog d1 = new Dog() ;
    Dog d2 = d1 ;
    
  • Object references can be compared using == and != .
    • Example 1:
    Dog d1 = new Dog() ;
    Dog d2 = new Dog() ;
    boolean result = d1 == d2;
    // result is false since d1 and d2 refer to two different objects.
    
    • Example 2:
    Dog d1 = new Dog() ;
    Dog d2 = d1 ;
    boolean result = d1 == d2;
    // result is true since d1 and d2 refer to the same object.
    
  • An object reference can be compared with null, using == or !=, to determine if the reference actually references an object.
    • Example:
    Dog d1 = null;
    Dog d2 = new Dog();
    
    System.out.println(d1 == null); // true
    System.out.println(d2 == null); // false
    System.out.println(d2 != null); // true
    
    • Note: Do not access instance variables or methods of a null object, it will lead to NullPointerException.

(3) Ways to Compare Two Objects

  • Two ways to compare two object references:
    • Compare two object references using == and !=
    • Compare two object references using the equals() method
  • Classes often define their own equals method, which can be used to specify the criteria for equivalency for two objects of the class.
  • The equivalency of two objects is most often determined using attributes from the two objects.
  • (AP Exam Exclusion: overriding the equals() method)

3. Exercises