Boolean Expressions and If Statement Lesson
A Jupyter Notebook for Boolean Expressions and If Statements
boolean condition = true;
if (condition == true) {
System.out.println("This code executes");
}
// Prints: This code executes
if (condition == false) {
System.out.println("This code does not execute");
}
// There is no output for the above statement
boolean condition = false;
if (condition){
System.out.println("condition is true");
}
else{
System.out.println("condition is not true");
}
// Prints: condition1 is not true
int classGrade = 76;
char grade;
if (classGrade >= 90) {
grade = 'A';
} else if (classGrade >= 80) {
grade = 'B';
} else if (classGrade >= 70) {
grade = 'C';
} else if (classGrade >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println(grade);
int month = 9;
String monthName;
switch (month) {
case 1: monthName = "January";
break;
case 2: monthName = "February";
break;
case 3: monthName = "March";
break;
case 4: monthName = "April";
break;
case 5: monthName = "May";
break;
case 6: monthName = "June";
break;
case 7: monthName = "July";
break;
case 8: monthName = "August";
break;
case 9: monthName = "September";
break;
case 10: monthName = "October";
break;
case 11: monthName = "November";
break;
case 12: monthName = "December";
break;
default: monthName = "Invalid month";
break;
}
System.out.println(monthName);
De Morgan's Law
Laws that define how we can negate an AND statement and how we can negate an OR statement. De Morgan’s Laws simply state: !(a && b) is equivalent to !a || !b and !(a || b) is equivalent to !a && !b. not (a and b) is the same as (not a) or (not b) and not (a or b) is the same as (not a) and (not b)
public class DeMorgansAndTest
{
public static void main(String[] args)
{
int x = 13;
int y = 151;
System.out.println(!(x<15 && y > 150));
System.out.println(!(x<15) || !(y > 150));
}
}
DeMorgansAndTest.main(null)
public class DeMorgansAndTest
{
public static void main(String[] args)
{
int x = 28;
int y = 100;
System.out.println(!(x<21 || y > 130));
System.out.println(!(x<21) && !(y > 130));
}
}
DeMorgansAndTest.main(null)