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 reference equality, not value 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 method 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:
1
2
3
4
5
6
7
8
9
10
11
publicclassTest{publicstaticvoidmain(){Stringa="Hello";Stringb=newString("Hello");System.out.println(a==b);}}Test.main()//output is false because the strings are objects so the data in the objects are different thus it prints false even if the values are the same
1
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
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:
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 multiple levels of decision-making within a program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
publicclassNested{publicstaticvoidmain(){intx=5;inty=-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()
1
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
publicclassCompound{publicstaticvoidmain(){intage=25;booleanisStudent=true;if(age>=18&&isStudent){System.out.println("You are an adult student.");}elseif(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()
1
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 ||).
1
2
3
4
5
6
7
8
9
10
11
12
publicclassShort{publicstaticvoidmain(){booleancondition1=true;booleancondition2=false;if(condition1||condition2){System.out.println("This will be printed.");}}}Short.main()
1
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.”
importjava.util.Scanner;publicclassGradeCalculator{publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);System.out.print(" Enter your midterm score (0-100): \n");intmidtermScore=scanner.nextInt();System.out.print(midtermScore);System.out.print("\n Enter your final exam score (0-100): \n");intfinalExamScore=scanner.nextInt();System.out.print(finalExamScore);System.out.print("\n Did you complete the homework (yes/no): \n");StringhomeworkComplete=scanner.next().toLowerCase();System.out.print(homeworkComplete);// write code herechargrade;if(homeworkComplete.equals("no")){grade='F';System.out.println("Your final grade is: "+grade);}else{intaverageScore=(midtermScore+finalExamScore)/2;if(averageScore>=70){grade='P';System.out.println("Your final grade is: "+grade);}else{grade='F';System.out.println("Your final grade is: "+grade);}}}}GradeCalculator.main(null)
1
2
3
4
5
6
Enter your midterm score (0-100):
78
Enter your final exam score (0-100):
90
Did you complete the homework (yes/no):
yesYour final grade is: P
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 boolean 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
publicclassExample{publicstaticvoidmain(){booleanx=true;booleany=false;// Original expressionbooleanoriginalExp=!(x&&y);// Applying De Morgan's LawbooleanequivalentExp=!x||!y;// Checking if the results are equivalentSystem.out.println("Are the expressions equivalent? "+(originalExp==equivalentExp));}}Example.main()
1
Are the expressions equivalent? true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
publicclassExample2{publicstaticvoidmain(){booleanp=true;booleanq=true;// Original expressionbooleanoriginalExp2=!(p||q);// Applying De Morgan's LawbooleanequivalentExp2=!p&&!q;// Checking if the results are equivalentSystem.out.println("Are the expressions equivalent? "+(originalExp2==equivalentExp2));}}Example2.main()
1
Are the expressions equivalent? true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
publicclassExample3{publicstaticvoidmain(){booleana=true;booleanb=false;booleanc=true;// Original expressionbooleanoriginalExp3=!(a&&b)||(c||!b);// Applying De Morgan's LawbooleanequivalentExp3=(!a||!b)||(c||b);// Checking if the results are equivalentSystem.out.println("Are the expressions equivalent? "+(originalExp3==equivalentExp3));}}Example3.main()
1
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)
4. !(A < (B > C)) A >= !(B > C) -> (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.
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.
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.
importjava.util.Scanner;publicclassPasswordChecker{privateintlength;privatebooleanuppercase;privatebooleanlowercase;privatebooleandigit;privatebooleanspecial;publicPasswordChecker(intlength,booleanuppercase,booleanlowercase,booleandigit,booleanspecial){this.length=length;this.uppercase=uppercase;this.lowercase=lowercase;this.digit=digit;this.special=special;}publicbooleancheckUppercase(StringmyPassword){for(inti=0;i<myPassword.length();i++){if(Character.isUpperCase(myPassword.charAt(i))){returntrue;}}System.out.println("Password contains no uppercase characters");returnfalse;}publicbooleancheckLowercase(StringmyPassword){for(inti=0;i<myPassword.length();i++){if(Character.isLowerCase(myPassword.charAt(i))){returntrue;}}System.out.println("Password contains no lowercase characters");returnfalse;}publicbooleancheckDigit(StringmyPassword){for(inti=0;i<myPassword.length();i++){if(Character.isDigit(myPassword.charAt(i))){returntrue;}}System.out.println("Password contains no digits");returnfalse;}publicbooleancheckSpecial(StringmyPassword){Patternp=Pattern.compile("[^a-z0-9 ]",Pattern.CASE_INSENSITIVE);Matcherm=p.matcher(myPassword);booleanres=m.find();if(res){returntrue;}System.out.println("Password contains no special characters");returnfalse;}publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);System.out.print("Enter your password: ");StringmyPassword=scanner.nextLine();PasswordCheckercheck1=newPasswordChecker(8,true,true,true,false);booleanisUppercaseValid=check1.checkUppercase(myPassword);booleanisLowercaseValid=check1.checkLowercase(myPassword);booleanisDigitValid=check1.checkDigit(myPassword);booleanisSpecial=check1.checkSpecial(myPassword);if(myPassword.length()>=8&&isUppercaseValid&&isLowercaseValid&&isDigitValid&&isSpecial){System.out.println("Password is valid");}else{System.out.println("Password is invalid");}}}PasswordChecker.main(null);
1
2
3
4
Enter your password: Password contains no uppercase characters
Password contains no digits
Password contains no special characters
Password is invalid