Home
Time Box
Calculator
Snake
Blogs
Hacks

Unit 3 Lesson • 29 min read


Lessons

3.1

Learning Objective

Types of Rational Operators

All operators give a true or False value

Operators SHOULD NOT be used on String . String comparisons should be done using .equal or .compareTo

Comparing Numbers

Select two numbers and check their relation:

public class Test {
    public static void main(){
        String a = "Hello";
        String b = new String("Hello");

        System.out.println( a == b);
    }
}
Test.main()
false

3.2 3.3 and 3.4

Learning Objective

We all know how if and else statements work

We all know how if and else statements work

Syntax

Interactive Flip Cards

if-else Syntax

        if (condition) {
            // Code to execute if the condition is true
        } else {
            // Code to execute if the condition is false
        }
      

else-if Syntax

        if (condition1) {
            // Code to be executed if condition1 is true
        } else if (condition2) {
            // Code to be executed if condition2 is true
        } else if (condition3) {
            // Code to be executed if condition3 is true
        } else {
            // Code to be executed if none of the conditions are true
        }
      

</html>

3.5

Learning Objectives:

Nested if-else statements

Nested if-else statements allow for __multiple__ levels of decision-making within a program.

public class Nested {
    public static void main() {
        int x = 5;
        int y = -10;

        if (x > 0) {
            if (y > 0) {
                System.out.println("Both x and y are positive.");
            } else {
                System.out.println("x is positive, but y is not.");
            }
        } else {
            System.out.println("x is not positive.");
        }
            }
}
Nested.main()
x is positive, but y is not.

Compound Boolean Expressions:

Compound boolean expressions involve using ____logical__ operators like && (and) and || (or) to combine multiple conditions.

public class Compound {
    public static void main(){
        int age = 25;
        boolean isStudent = true;

        if (age >= 18 && isStudent) {
            System.out.println("You are an adult student.");
        } else if (age >= 18 || isStudent) {
            System.out.println("You are either an adult or a student.");
        } else {
            System.out.println("You are neither an adult nor a student.");
        }
            }
}
Compound.main()
You are an adult student.

Short-Circuited Evaluation:

Short-circuited evaluation is an __optimization__ technique where the second condition in a compound expression is only evaluated if the first condition is true (for &&) or false (for ||).

public class Short {
    public static void main() {
        boolean condition1 = true;
        boolean condition2 = false;

        if (condition1 || condition2) {
            System.out.println("This will be printed.");
        }
    }
}

Short.main()
This will be printed.

Coding Practice

Calculate the final grade based on the following criteria:

import java.util.Scanner;

public class GradeCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your midterm score (0-100): ");
        int midtermScore = scanner.nextInt();

        System.out.print("Enter your final exam score (0-100): ");
        int finalExamScore = scanner.nextInt();

        System.out.print("Did you complete the homework (yes/no): ");
        String homeworkComplete = scanner.next().toLowerCase();

        double grade; 

        if (midtermScore >= 0 && midtermScore <= 100 && finalExamScore >= 0 && finalExamScore <= 100) {
            double midtermWeight = 0.4;
            double finalExamWeight = 0.4;
            double homeworkWeight = 0.2;

            double weightedMidterm = midtermScore * midtermWeight;
            double weightedFinalExam = finalExamScore * finalExamWeight;

            if (homeworkComplete.equals("yes")) {
                grade = weightedMidterm + weightedFinalExam + 10;
            } else {
                grade = weightedMidterm + weightedFinalExam;
            }

            System.out.println("Your final grade is: " + grade);
        } else {
            System.out.println("Invalid input for midterm or final exam scores.");
        }

        scanner.close();
    }
}
GradeCalculator.main(null)

Enter your midterm score (0-100): Enter your final exam score (0-100): Did you complete the homework (yes/no): Your final grade is: 70.0

3.6

Learning Objective

De Morgan’s Law

De Morgan's Law provides a set of rules for negating complex boolean expressions.

Example:

Using && operators:

image

Using || operator:

image

More:

A bit more complex:

image

Proving the law using tables

image

public class Example {
    public static void main(){
        boolean x = true;
        boolean y = false;

        // Original expression
        boolean originalExp = !(x && y);

        // Applying De Morgan's Law
        boolean equivalentExp = !x || !y;

        // Checking if the results are equivalent
        System.out.println("Are the expressions equivalent? " + (originalExp == equivalentExp));

    }
}
Example.main()
Are the expressions equivalent? true
public class Example2 {
    public static void main(){
        boolean p = true;
        boolean q = true;

        // Original expression
        boolean originalExp2 = !(p || q);

        // Applying De Morgan's Law
        boolean equivalentExp2 = !p && !q;

        // Checking if the results are equivalent
        System.out.println("Are the expressions equivalent? " + (originalExp2 == equivalentExp2));
    }
}

Example2.main()
Are the expressions equivalent? true
public class Example3 {
    public static void main(){
        boolean a = true;
        boolean b = false;
        boolean c = true;

        // Original expression
        boolean originalExp3 = !(a && b) || (c || !b);

        // Applying De Morgan's Law
        boolean equivalentExp3 = (!a || !b) || (c || b);

        // Checking if the results are equivalent
        System.out.println("Are the expressions equivalent? " + (originalExp3 == equivalentExp3));

    }
}

Example3.main()
Are the expressions equivalent? true

De Morgan’s Law Practice

Negate the following expressions:

1. !(A || B)

(!A && !B))

2. !(A || B && C)

(!A && !B || !C)

3. !(A && (B || C))

(!A || !B && !C)

3.7

Learning Objective

image

An if statement using == to compare myHouse and momsHouse will be true but false for myHouse and annasHouse because the objects are not the same even though they have same parameters. This means that == will only return true if it is the same object, not a reference or copy of that object.

String a = "Hello";
String b = "Hello";
String c = a;
String d = new String("Hello");

System.out.println(a == c);
System.out.println(d == b);
System.out.println(a == b);
System.out.println(a == d);
true
false


true
false

image

When you want to compare objects you can use the .equal() method, it will return true if the objects have the same attributes even if they aren’t identical.

String a = "Hello";
String b = "Hello";
String c = a;
String d = new String("Hello");

System.out.println(a.equals(c));
System.out.println(d.equals(b));
System.out.println(a.equals(b));
System.out.println(a.equals(d));
true
true
true
true

Hacks

Coding Practice

Create a program that validates a user’s password based on the following criteria:

  1. The password must be at least 8 characters long.
  2. The password must contain at least one uppercase letter.
  3. The password must contain at least one lowercase letter.
  4. The password must contain at least one digit (0-9).
  5. The password must contain at least one special character (!, @, #, $, %, ^, &, *).

Write a Java program that prompts the user to enter a password and then checks if it meets the above criteria. If the password meets all the criteria, print “Password is valid.” If not, print a message indicating which criteria the password fails to meet.

How the code works

import java.util.Scanner;

public class PasswordValidator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a password: ");
        String password = scanner.nextLine();
        scanner.close();

        if (isValidPassword(password)) {
            System.out.println("Password is valid.");
        } else {
            System.out.println("Password is invalid. It must meet the following criteria:");
            if (password.length() < 8) {
                System.out.println("- The password must be at least 8 characters long.");
            }
            if (!containsUppercase(password)) {
                System.out.println("- The password must contain at least one uppercase letter.");
            }
            if (!containsLowercase(password)) {
                System.out.println("- The password must contain at least one lowercase letter.");
            }
            if (!containsDigit(password)) {
                System.out.println("- The password must contain at least one digit (0-9).");
            }
            if (!containsSpecialCharacter(password)) {
                System.out.println("- The password must contain at least one special character (!, @, #, $, %, ^, &, *).");
            }
        }
    }

    public static boolean isValidPassword(String password) {
        return password.length() >= 8
                && containsUppercase(password)
                && containsLowercase(password)
                && containsDigit(password)
                && containsSpecialCharacter(password);
    }

    public static boolean containsUppercase(String password) {
        for (char ch : password.toCharArray()) {
            if (Character.isUpperCase(ch)) {
                return true;
            }
        }
        return false;
    }

    public static boolean containsLowercase(String password) {
        for (char ch : password.toCharArray()) {
            if (Character.isLowerCase(ch)) {
                return true;
            }
        }
        return false;
    }

    public static boolean containsDigit(String password) {
        for (char ch : password.toCharArray()) {
            if (Character.isDigit(ch)) {
                return true;
            }
        }
        return false;
    }

    public static boolean containsSpecialCharacter(String password) {
        String specialCharacters = "!@#$%^&*";
        for (char ch : password.toCharArray()) {
            if (specialCharacters.contains(String.valueOf(ch))) {
                return true;
            }
        }
        return false;
    }
}

PasswordValidator.main(null);
Enter a password: Password is valid.