Lessons
3.1
Learning Objective
- Evaluate Boolean expressions that use relational operators in program code
Types of Rational Operators
- Operators
- Primitives
- Equal to: ==
- Not Equal to: !=
- Arithmetic
- Greater than: >
- Less than: >
- Greater than or equal to: >=
- Less than or equal to: <=
All operators give a true
or False
value
Operators SHOULD NOT be used on String . String comparisons should be done using .equal or .compareTo
- This is because
- In Java, strings should not be compared using the == operator because it checks for ____ equality, not ____ equality.
- When you use == with objects (including strings), it checks if the references to the objects are the same. In other words, it checks if they point to the same ____ in the memory.
- String literals in Java are stored in a special memory area called the “String Pool”. When you create a string literal, Java checks if a string with the same content already exists in the pool. If it does, it returns a reference to that existing string; if not, it creates a new string.
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
- Represent branching logical processes by using conditional statements
We all know how if and else statements work
We all know how if and else statements work
Syntax
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:
- Understand nested if-else statements and their role in representing branching logical processes.
- Evaluate compound boolean expressions using logical operators like
&&
and||
. - Introduce short-circuited evaluation in compound boolean expressions.
Nested if-else statements
Nested if-else statements allow for ____ 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 ____ 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 ____ 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:
- If the student didn’t complete homework, the grade is automatically “F.”
- If the student completed homework and the average of midterm and final exam scores is >= 70, the grade is “Pass.”
- Otherwise, the grade is “Fail.”
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): \n");
int midtermScore = scanner.nextInt();
System.out.print(midtermScore);
System.out.print("\n Enter your final exam score (0-100): \n");
int finalExamScore = scanner.nextInt();
System.out.print(finalExamScore);
System.out.print("\n Did you complete the homework (yes/no): \n");
String homeworkComplete = scanner.next().toLowerCase();
System.out.print(homeworkComplete);
int grade = (midtermScore + finalExamScore)/2;
// write code here
if (homeworkComplete == "no") {
System.out.println("\n Your final grade is: F");
} else {
System.out.println("\n Your final grade is: " + grade);
}
System.out.println("\n Your final grade is: " + grade);
scanner.close();
}
}
GradeCalculator.main(null)
Enter your midterm score (0-100):
100
Enter your final exam score (0-100):
60
Did you complete the homework (yes/no):
yes
Your final grade is: 80
Your final grade is: 80
3.6
Learning Objective
- Compare and contrast equivalent Boolean expressions
De Morgan’s Law
- Augustus De Morgan was a 19th century mathematician whose laws or rules about ____ logic allow us to simplify expressions when they are negated Given two Boolean variables a and b:
De Morgan's Law provides a set of rules for negating complex boolean expressions.
Example:
Using &&
operators:
Using ||
operator:
More:
- !(x > 0) → (x <= 0)
- Distributing a “not” with a boolean expression “flips” the relational operator to the opposite relational operator
- !(x < 0) → (x >= 0)
- !(x >= 0) → (x < 0)
- !(x == 0) → (x != 0)
- ! (x != 0) → ( x == 0)
A bit more complex:
Proving the law using tables
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)
is (!A && !B)
2. !(A || B && C)
is (!A && !B || !C)
3. !(A && (B || C))
is (!A || !B && !C)
3.7
Learning Objective
- Compare object reference using boolean expressions in program code
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
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
- Complete popcorn hacks - 0.1 points
- Coding hacks - 0.8 points
- Complexity: 0.4 points
- Functionality: 0.4 points
Coding Practice
Create a program that validates a user’s password based on the following criteria:
- The password must be at least 8 characters long.
- The password must contain at least one uppercase letter.
- The password must contain at least one lowercase letter.
- The password must contain at least one digit (0-9).
- 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.
import java.security.SecureRandom;
import java.util.Scanner;
public class PasswordCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your password: ");
String password = scanner.next();
System.out.println("Password: " + password);
boolean hasUpperCase = false;
boolean hasLowerCase = false;
boolean hasDigit = false;
boolean hasSpecialChar = false;
// Check password length for 8 characters
if (password.length() < 8) {
System.out.println("Your password is too short");
} else {
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.isUpperCase(c)) {
hasUpperCase = true;
} else if (Character.isLowerCase(c)) {
hasLowerCase = true;
} else if (Character.isDigit(c)) {
hasDigit = true;
} else if (isSpecialCharacter(c)) {
hasSpecialChar = true;
}
}
if (!hasUpperCase) {
System.out.println("Your password needs an uppercase character");
}
if (!hasLowerCase) {
System.out.println("Your password needs a lowercase character");
}
if (!hasDigit) {
System.out.println("Your password needs a digit (0-9)");
}
if (!hasSpecialChar) {
System.out.println("Your password needs a special character (!, @, #, $, %, ^, &, *)");
}
// If the password doesn't meet criteria, generate a random password
if (!(hasUpperCase && hasLowerCase && hasDigit && hasSpecialChar)) {
String generatedPassword = generateRandomPassword();
System.out.println("Generated password: " + generatedPassword);
}
}
scanner.close();
}
// Helper function to check if a character is a special character
private static boolean isSpecialCharacter(char c) {
return "!@#$%^&*".indexOf(c) != -1;
}
// Helper function to generate a random password
private static String generateRandomPassword() {
String upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerChars = "abcdefghijklmnopqrstuvwxyz";
String digitChars = "0123456789";
String specialChars = "!@#$%^&*";
SecureRandom random = new SecureRandom();
StringBuilder password = new StringBuilder();
password.append(upperChars.charAt(random.nextInt(upperChars.length())));
password.append(lowerChars.charAt(random.nextInt(lowerChars.length())));
password.append(digitChars.charAt(random.nextInt(digitChars.length())));
password.append(specialChars.charAt(random.nextInt(specialChars.length())));
while (password.length() < 8) {
int category = random.nextInt(4);
switch (category) {
case 0:
password.append(upperChars.charAt(random.nextInt(upperChars.length())));
break;
case 1:
password.append(lowerChars.charAt(random.nextInt(lowerChars.length())));
break;
case 2:
password.append(digitChars.charAt(random.nextInt(digitChars.length())));
break;
case 3:
password.append(specialChars.charAt(random.nextInt(specialChars.length())));
break;
}
}
return password.toString();
}
}
PasswordCheck.main(null);
Enter your password: Password: passWord!@Theo
Your password needs a digit (0-9)
Generated password: Xk3!m84*
Extra
I added a password generator which just takes from a bank of characters and symbols and generates a password of a given length.