3.1 Boolean Expressions

Java’s relational operators

  • equal to: ==
  • not equal to: !=
  • less than: <
  • greater than: >
  • less than or equal to: <=
  • greater than or equal to >=

Hack!

int myAge = 15;
int otherAge = 45; 

using these integers, determine weather the following statements are True or False

Screenshot 2024-09-15 at 10 00 54 PM

Hack 1 answers:

  1. true
  2. true
  3. true
  4. false
  5. false
  6. true

Strings

popcorn hack

whats wrong with this code? (below)

// PROBLEM: Before I changed it, Alisha was not in quotes
String myName = "Alisha";

// PROBLEM: Anika and Alisha weren't in quotes
myName != "Anika";
myName == "Alisha";
true

comparison of string objects should be done using String methods, NOT integer methods.

  • .equals()
  • .compareTo()
String myName = "Alisha";
boolean areNamesEqual = myName.equals("Alisha");  

if (areNamesEqual) {
    System.out.println("True");
} else {
    System.out.println("False");
}

True

Homework Question

Screenshot 2024-09-16 at 8 05 24 AM

What is the precondition for num?

public class CheckDigit {
    /**
     * Goes above and byeond by actually counting the digits rather than just checking
     * if (num >= 0 && num <= 999999)
     */
    public static boolean preCondition(int num) {
        if (num < 0) { return false; }

        int digits = 0;
        while (true) {
            if (num / 10 >= 1) {
                digits++;
                num = num/10;
            } else {
                digits++;
                break;
            }
        }
        return digits >= 1 && digits <= 6;
    }
}
CheckDigit.preCondition((int) 12345678);
8





false