2.5 Compound Boolean Expressions
From CS Awesome 2CC BY-NC-SA 4.0Original page
Java2 class periods5 exercises11 graded tests
Files
2.5 Compound Boolean Expressions
Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.
And (&&), Or (||), and Not (!)
What if you want two things to be true before the body of the conditional is executed? Use && as a logical and to join two Boolean expressions and the body of the condition will only be executed only if both are true.
Exercise 1
What if you want to go out and your parents say you can go out if you clean your room and do your homework? Run the code and try different values for cleanedRoom and didHomework and see what they have to be for it to print You can go out.
Open the
01-compoundAndfolder and editTest1.java. Press Run to try it; Run Tests checks it (2 tests).
What if it is okay if only one of two things is true? Use || as a logical or to join two Boolean expressions and the body of the condition will be executed if one or both are true.
Exercise 2
For example, your parents might say you can go out if you can walk or they don’t need the car. Try different values for walking and carIsAvailable and see what the values have to be to print You can go out.
Open the
02-compoundOrfolder and editTest2.java. Press Run to try it; Run Tests checks it (2 tests).
In English, we often use an exclusive-or like in the sentence “do you want to be player 1 or player 2?” where you can’t be both player 1 and player 2. In programming, the or-operator is an inclusive-or which means that the whole expression is true if either one or the other or both conditions are true.
With numerical values, the or (||) operator is often used to check for error conditions on different ends of the number line, while the and (&&) operator is often used to see if a number is in an range.
Exercise 3
Explore how && and || are used with numbers below. Try different values for score like -10 and 110 in the code.
Open the
03-compound-number-rangefolder and editTestNum.java. Press Run to try it; Run Tests checks it (1 test). Its test checks your code, not what it prints: “Code has been changed”.
The not (!) operator can be used to negate a boolean value. We’ve seen ! before in != (not equal). If you use ! in expressions with && and ||, be careful because the results are often the opposite of what you think it will be at first. We’ll see examples of this in the next lesson.
Exercise 4
The code says if homework is not done, you can’t go out. Try different values for homeworkDone.
Open the
04-not-operatorfolder and editTestNot.java. Press Run to try it; Run Tests checks it (1 test). Its test checks your code, not what it prints: “Code has been changed”.
In Java, ! will be executed before &&, and && will be executed before ||, unless there are parentheses. Anything inside parentheses is executed first.
Truth Tables
The following table (also called a truth table) shows the result for P && Q when P and Q are both expressions that can be true or false. An expression involving logical operators like P && Q evaluates to a boolean value, true or false. As you can see below the result of P && Q is only true if both P and Q are true.
| P | Q | P && Q |
|---|---|---|
| true | true | true |
| false | true | false |
| true | false | ? |
| false | false | false |
Check your understanding: The truth table above is missing one result. What is the result of
P && QwhenP=trueandQ=false? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#truthTableFill
The following table shows the result for P || Q when P and Q are both expressions that can be true or false. As you can see below the result of P || Q is true if either P or Q is true. It is also true when both of them are true.
| P | Q | P || Q |
|---|---|---|
| true | true | true |
| false | true | ? |
| true | false | true |
| false | false | false |
Check your understanding: The truth table above is missing one result. What is the result of
P || QwhenP=falseandQ=true? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#truthTableFill2
Check your understanding: What is printed when the following code executes and x has been set to 3 and y has been set to 9?
if (x > 0 && (y / x) == 3) { System.out.println("first case"); } else { System.out.println("second case"); }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#traceCompoundBools
Check your understanding: What is printed when the following code executes and x has been set to 3 and y has been set to 6?
if (x > 0 && (y / x) == 3) { System.out.println("first case"); } else { System.out.println("second case"); }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#traceCompoundBools2
Check your understanding: What is printed when the following code executes and x has been set to 3 and y has been set to 6? Notice that it is now an or (||) instead of and (&&).
if (x > 0 || (y / x) == 3) { System.out.println("first case"); } else { System.out.println("second case"); }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#qcbc_or
Short Circuit Evaluation
Both && and || use short circuit evaluation. That means that the second expression (on the right of the operator) isn’t necessarily checked, if the result from the first expression is enough to tell if the compound boolean expression is true or false:
- If two boolean values/expressions are combined with a logical or (
||) and the first expression istrue, then the second expression won’t be executed, since only one needs to betruefor the result to betrue. - If two boolean values/expressions are combined with a logical and (
&&) and the first expression isfalse, then the second expression won’t be executed. If the first expression isfalse, the result will befalse, since both sides of the&&need to betruefor the result to betrue.
Check your understanding: What is printed when the following code executes and x has been set to 0 and y to 3?
if (x > 0 && (y / x) == 3) { System.out.println("first case"); } else { System.out.println("second case"); }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#shortCircuit1
Check your understanding: What is printed when the following code executes and x has been set to zero and y is set to 3?
if (x == 0 || (y / x) == 3) { System.out.println("first case"); } else { System.out.println("second case"); }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#shortCircuit2
Coding Challenge: Truth Tables POGIL
We encourage you to do this activity as a POGIL (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a POGIL role and works together to solve the problems, making sure that everyone in the team participates and learns.
Explore the following problems with your group:
- Draw or print a Venn diagram of 4 intersecting circles. Put the names of the 4 people in your group one in each circle. Write down the age of each person in your group in the circles. If two or more people are the same age, put the age in the intersecting parts of their circles. Write a Boolean expression that compares the age of each person in the group using
==,<,>, and&&, for example Ada’s age>Alan’s age&&Alan’s age==Grace’s age. Then, ask each person in your group their favorite movie. If two or more people have the same favorite movie, put the movie in the intersecting parts of their circles. Write a Boolean expression that compares the favorite movies in the group using==,!=, and&&, for example Ada’s movie==Alan’s movie&&Alan’s movie!=Grace’s movie. Think of 1 more comparison and write it in the circles and as a Boolean expression. Share the Boolean expressions with the class. (Thank you to Jill Westerlund of Hoover High School and Art Lopez of Sweetwater High School for this activity suggestion). - Write the sentence “If it’s sunny, OR if the temperature is greater than 80 and it’s not raining, I will go to the beach.” as a Java if statement using an int variable
temperatureand boolean variablessunnyandraining. If the conditional is true, print out “Go to the beach!”. So, you will go to the beach on days that it is sunny in any temperature, or you will go to the beach on days when the temperature is over 80 degrees and it’s not raining. - Complete a truth table for the if statement that you wrote in #2 with columns for sunny, temperature > 80, raining, and go to the beach.
- Write Java code below to test your if statement and try all the values in your truth table to see if you filled it out correctly. You will need test case for each of the 8 rows in your truth table, for example when sunny is true and false, when raining is true or false, and for a value of temperature greater than 80, for example 90, and less than 80, for example 60.
Exercise 5
Challenge-truthtables: Test your boolean expression in an if statement below.
Open the
05-challenge-truthtablesfolder and editTruthTable.java. Press Run to try it; Run Tests checks it (5 tests).
Summary
- (AP 2.5.A.1) Logical operators
!(not),&&(and), and||(or) are used with Boolean values.A && Bistrueif bothAandBaretrue.A || Bistrueif eitherAorB(or both) aretrue.!AistrueifAisfalse.
- (AP 2.5.A.1)
!has precedence (is executed before)&&which has precedence over||. (Parentheses can be used to force the order of execution in a different way.) - (AP 2.5.A.1) An expression involving logical operators evaluates to a Boolean value.
- (AP 2.5.A.2) Short-circuit evaluation occurs when the result of a logical operation using
&&or||can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated. (If the first expression istruein an||operation, the second expression is not evaluated since the result is true. If the first expression isfalsein an&&operation, the second expression is not evaluated since the result is false.)
AP Practice
Check your understanding: Consider the following code segment. What is printed as a result of executing the code segment?
int x = 10; int y = 5; if (x % 2 == 0 && y % 2 == 0 || x > y) { System.out.print("First "); if (y * 2 == x || y > 5 && x <= 10) { System.out.print("Second "); } else { System.out.print("Third "); } }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#AP-compound-bools
Boolean Game
Try the game below written to practice Booleans. Click on Booleans, look at the color and number in the block and evaluate the boolean expression to choose true or false. Then, check on Compound for an added challenge. We encourage you to work in pairs and see how high a score you can get.
Play the game on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html#boolean-game
For teachers
2.5 Compound Boolean Expressions
Students read CSAwesome2's “Compound Boolean Expressions” in CS Room and work through its 5 Java coding exercises.
- Time: 2 class periods
- Tests: 11 in 5 graded exercises, set up for you when you import the lesson
Goals
- (AP 2.5.A.1) Logical operators
!(not),&&(and), and||(or) are used with Boolean values.A && Bistrueif bothAandBaretrue.A || Bistrueif eitherAorB(or both) aretrue.!AistrueifAisfalse.
- (AP 2.5.A.1)
!has precedence (is executed before)&&which has precedence over||. (Parentheses can be used to force the order of execution in a different way.) - (AP 2.5.A.1) An expression involving logical operators evaluates to a Boolean value.
- (AP 2.5.A.2) Short-circuit evaluation occurs when the result of a logical operation using
&&or||can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated. (If the first expression istruein an||operation, the second expression is not evaluated since the result is true. If the first expression isfalsein an&&operation, the second expression is not evaluated since the result is false.)
Before class
- Import the lesson into your class from the Lessons page, or with New assignment → Use a lesson. It arrives as a draft with its tests already set up.
- Publish it.
- The original page, with its fill-in and multiple-choice questions, is on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-5-compound-ifs.html
- CS Awesome's own teacher materials: the CS Awesome teacher site
In class
- Students read
README.md. Questions that need CS Awesome's interactive widgets link back to it. - Students do exercises 01–05, each in its own folder, pressing Run to try their code.
- Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.
Exercises
| Folder | File | Grading | Tests |
|---|---|---|---|
01-compoundAnd | Test1.java | Autograded | 2 |
02-compoundOr | Test2.java | Autograded | 2 |
03-compound-number-range | TestNum.java | Checks code text only | 1 |
04-not-operator | TestNot.java | Checks code text only | 1 |
05-challenge-truthtables | TruthTable.java | Autograded | 5 |
Teachers can download a reference solution after signing in.