CSA Blog

Ian Wu

Unit 3 Team Teach - 3.7 Comparing Objects

3.1: Boolean Expressions 3.2: If Control Flow 3.3: If Else 3.4: Else If 3.5: Compound Booleans 3.6: Equivalent Booleans 3.7: Comparing Objects 3.8: Homework

3.7 Comparing Objects

short-circuited evaluation:

expression can be determined by only looking at the first operand.

function isEven(num) {
    return num % 2 === 0;
}

function isPositive(num) {
    return num > 0;
}

let number = 10;

// Short-circuit with &&
if (isEven(number) && isPositive(number)) {
    console.log(number + " is even and positive.");
} else {
    console.log(number + " does not meet the criteria.");
}

|   function isEven(num) {

<identifier> expected



|       return num % 2 === 0;

illegal start of expression

Short-Circuit Behavior:

  • && (Logical AND): The expression isEven(number) && isPositive(number) is evaluated.
    • JavaScript first evaluates isEven(number). - If this returns false, the whole expression will short-circuit, and isPositive(number) will not be evaluated.
  • If isEven(number) is true, then isPositive(number) is evaluated.

Comparing Objects

In java there are two different methods to compare objects but there is a difference between the == operator and the equals() method.

## == operator

This operator verifies if two references refer to the same object in memory, without evaluating the objects' values or attributes.
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = num1;
Integer num4 = new Integer(100);

System.out.println(num1 == num3); // true (same reference)
System.out.println(num1 == num2); // true (cached integers between -128 and 127)
System.out.println(num1 == num4); // false (different references)
This compares the integer as num1 == num3 because they both equal the same integer so it's true. num1 == num2 because when they are both assigned the value 100 they point to the same reference so they become true. num1 == num4 even though they have the same values they are different because it's a new integer so it becomes false because they don't have the same reference point.

equals() method

This method checks the values or attributes of two objects. In custom classes, it is commonly overridden to offer a meaningful comparison based on the class’s specific attributes. It focuses on value rather reference points.

Integer num1 = 100;
Integer num2 = 100;
Integer num3 = new Integer(100);

System.out.println(num1.equals(num2)); // true (same value)
System.out.println(num1.equals(num3)); // true (same value)

This compares the values by their objects, not their references. num1.equals(num2) checks if the values are the same between the 2 but since they both have a value of 100 they are equal so it becomes true. This ignores if the objects have the same or different reference point. num1.euals(num3) even though it has a new integer and it’s different from num1 they are still the same because they have the same value so it makes it true.

Popcorn hack

Would the sharons house and my house be the same?

Yes, since the if statement checks if the house size and color are the same. Both the houses are green and have a size of 150.

class House {
    private String color;
    private int size;

    public House(String color, int size) {
        this.color = color;
        this.size = size;
    }

    // Override equals method to compare House objects by content
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;  // Check if same object reference
        if (obj == null || getClass() != obj.getClass()) return false;  // Check if same class
        House house = (House) obj;
        return size == house.size && color.equals(house.color);  // Compare attributes
    }
}

House myHouse = new House("green", 150);
House anikasHouse = new House("green", 150);
House sharonsHouse = new House("green", 150);

// Correct comparison using equals()
System.out.println(myHouse.equals(sharonsHouse));  // This should return true
true

Unit 3 Team Teach - 3.6 Equivalent Booleans

3.1: Boolean Expressions 3.2: If Control Flow 3.3: If Else 3.4: Else If 3.5: Compound Booleans 3.6: Equivalent Booleans 3.7: Comparing Objects 3.8: Homework

3.6 Equivalent Boolean Expressions

  • There are multiple ways to represent the same boolean expression. To show that the are the same expression, wither prove that they can be simplified to the same expression using boolean properties and identitied or prove that they can be the same in all cases.
  • Using De Morgan’s Law to compare and contrast equivalent Boolean expressions

Logical operators reminder

  • && (AND):
    • Returns true only if both conditions are true.
    • Example: (condition1 && condition2) is true if both condition1 and condition2 are true.
  • || (OR):
    • Returns true if at least one of the conditions is true.
    • Example: (condition1 || condition2) is true if either condition1 or condition2 (or both) are true.
  • ! (NOT):
    • Negates the value of a condition; returns true if the condition is false, and vice versa.
    • Example: !(condition) is true if condition is false.

De Morgans Law

Screenshot 2024-09-25 at 3 48 47 AM

Screenshot 2024-09-25 at 3 49 40 AM

Distributing a “not” with a Boolean expression ‘flips’ the relationsal operator to the opposite relational operator

  • ex: !(x > 0) is equivalent to (x<= 0)

Popcorn Hack

Challenge Questions

  1. What is !(x == 0) equivalent to?
    • Apply De Morgan’s Law to find an equivalent expression.
  • x != 0
  1. Negate the expression (x < -5 || x > 10).
    • Use De Morgan’s Law to rewrite this expression in a different form.
  • (x > -5 || x < 10)
  • !(-5 < x < 10)

Truth Tables

  • evaluate and shoe equivalency in Boolean expressions
  • see al the possible outcomes that we will have.

Screenshot 2024-09-25 at 3 13 16 AM

Screenshot 2024-09-25 at 3 19 33 AM

Unit 3 Team Teach - 3.5 Compound Booleans

3.1: Boolean Expressions 3.2: If Control Flow 3.3: If Else 3.4: Else If 3.5: Compound Booleans 3.6: Equivalent Booleans 3.7: Comparing Objects 3.8: Homework

3.5 Compund Boolean expressions

Nested conditional statements

definition: if statements within other if statements

public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean isStudent = true;

        // Outer if-else block
        if (age >= 18) {
            // Nested if-else block inside the first condition
            if (isStudent) {
                System.out.println("You are an adult and a student.");
            } else {
                System.out.println("You are an adult.");
            }
        } else {
            System.out.println("You are not an adult.");
        }
    }
}

Simple Example of a Nested Conditional Statement

Let’s look at a very basic example of a nested conditional statement using if-else blocks.

Scenario:

We want to check if a person is an adult and, if they are, we want to know if they are also a student.

Compound Conditional Statement

A compound conditional statement is when two or more conditions are combined into a single if statement using logical operators like && (AND), || (OR), or ! (NOT). This allows us to check multiple conditions at once without needing to nest if statements.

Logical Operators:

  • && (AND): True if both conditions are true.
  • || (OR): True if at least one condition is true.
  • ! (NOT): Reverses the result of a condition (true becomes false, and false becomes true).

Example of a Compound Conditional Statement

Let’s say we want to check if a person is an adult and a student at the same time. Instead of using a nested if statement, we can use a compound conditional statement.

public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean isStudent = true;

        // Compound conditional using && (AND)
        if (age >= 18 && isStudent) {
            System.out.println("You are an adult and a student.");
        } else {
            System.out.println("Either you are not an adult, or you are not a student.");
        }
    }
}

common mistake: Dangling else

- Java does not care about indentation
- else always belongs to the CLOSEST if
- curly braces can be use to format else so it belongs to the FIRST 'if'

Popcorn hack

  • explain the purpose of this algorithm, and what each if condition is used for
    • determine which discounts apply to a certain student, including Basic, Premium, Student and Senior. It then displays the discounts if any that one is eligible for.
  • what would be output if input is
    • age 20
    • anual income 1500
    • student status: yes “You are eligible for a Student Discount.”
function checkMembershipEligibility() {
    // Get user input
    let age = parseInt(prompt("Enter your age:"));  // Age input
    let income = parseFloat(prompt("Enter your annual income:"));  // Annual income input
    let isStudent = prompt("Are you a student? (yes/no):").toLowerCase() === 'yes';  // Student status input

    // Initialize an empty array to hold results
    let results = [];

    // Check eligibility for different memberships

    // Basic Membership
    if (age >= 18 && income >= 20000) {
        results.push("You qualify for Basic Membership.");
    }

    // Premium Membership
    if (age >= 25 && income >= 50000) {
        results.push("You qualify for Premium Membership.");
    }

    // Student Discount
    if (isStudent) {
        results.push("You are eligible for a Student Discount.");
    }

    // Senior Discount
    if (age >= 65) {
        results.push("You qualify for a Senior Discount.");
    }

    // If no eligibility, provide a default message
    if (results.length === 0) {
        results.push("You do not qualify for any memberships or discounts.");
    }

    // Output all results
    results.forEach(result => console.log(result));
}

// Call the function to execute
checkMembershipEligibility();

Popcorn Hack #2

  • Write a program that checks if a person can get a discount based on their age and student status. You can define your own discount criteria! Use compound conditionals to determine the output.
int age = 30; // Change this value for testing
boolean isStudent = true; // Change this value for testing
boolean exists = false;

if (age * (exists? 1 : 0) % 20 == 0) {
    System.out.println("Eligible for 5% discount");
} else if (((age ^ 25) != 0) ^ Integer.MAX_VALUE > 0) {
    System.out.println("Eligible for 10% discount");
} else if (age + (isStudent ? 1 : 0) + (exists ? 1 : 0) < 40) {
    System.out.println("Elgibile for -20% discount");
} else {
    System.out.println("Not eligible for any discounts");
}
Eligible for 5% discount