U3 Boolean and If statements
Lesson on booleans and if statements!
APCSA Unit 3: College Board Learning Objectives and Standards
Learning Objectives
The objective of today’s lesson is to…
- Evaluate Boolean expressions that use relational operators in program code
Essential Knowledge
College Board wants you to know that…
- Primitive values and reference values can be compared using relational operators (i.e., == and !=)
- Arithmetic expression values can be compared using relational operators (such as <, >, <=, >=)
- An expression involving relational operators evaluates to a Boolean value
Warm Up
Answer the following questions as a group or individually. Write down your answers in your hacks notebook.
- What is a boolean?
- What values can a boolean represent? How many?
- What is an example of when we’d use a boolean?
Recap on Booleans
A boolean is a type of variable that can evaluate to true or false. In Java, there are various comparison operators that can be used in order to compare two values. What are some?
The format is val1 <oper> val2
, and will return a boolean given the state of the system. Like all booleans, this can only return two values true
or false
public class Example {
private static boolean isAdult = false;
private static int myAge = 16;
public static void main(String [] args){
if(myAge >= 18){
System.out.println("You are an adult!");
isAdult = true;
} else {
System.out.println("You are not an adult!");
}
System.out.println(isAdult);
}
}
Example.main(null);
You are not an adult!
false
Comparison Operators
Whenever you want to make a boolean statement (such as setting a boolean to be true or false), you want to use the "="
or "!="
sign and not the "=="
sign.
On the other hand, if you are ever trying to compare String objects, use the String methods such as .equals
or .compareTo
, NOT the Boolean expressions mentioned above.
Setup Class
Note the utilization of the compareTo
in a custom class in order to compare two classes
public class ComparisonExample implements Comparable<ComparisonExample> {
private int comp;
private int comp2;
public ComparisonExample(int _comp, int _comp2) {
this.comp = _comp;
this.comp2 = _comp2;
}
@Override
public int compareTo(ComparisonExample s) {
return Integer.compare(this.comp, s.comp);
}
public static int compare(ComparisonExample a, ComparisonExample b)
{
if(Integer.compare(a.comp, b.comp)==0){
return Integer.compare(a.comp2, b.comp2);
}
else {
return Integer.compare(a.comp, b.comp);
}
}
}
Comparing using compareTo
Describe this code and the code above using comments. Talk about how we define the compareTo
in the class definition and how that compares each instance of a class using a certain comparison variables.
In your notes Compare and contrast Comparator<>
and compareTo
ComparisonExample c = new ComparisonExample(2, 2);
ComparisonExample v = new ComparisonExample(2, 3);
System.out.println(c.compareTo(v)); // Allows comparison of these two instances of a class
System.out.println(ComparisonExample.compare(c, v)); // Also allows for the instances
if(ComparisonExample.compare(c, v) < 0){ // Using the comparison
System.out.println("This is less than!");
}
else { System.out.println("it is not"); }
0
-1
This is less than!
Comparing using .equals
You can use the .equals method to compare the contents of two strings. To test if the two strings are the same or not, you can use Sysout (System.out.println) so that the console will provide a value that is either true or false.
System.out.println("hello".equals("hello")); // will return true, since the strings are the same
System.out.println("Hello".equals("hello")); // will return false, as the one thing that separates these two strings is that the h is capitalized in the first string
true
false
Comparing two arrays
The code below compares the contents of two arrays to see if they are equal. It uses the equals
method. However, as we see below, this is rather shallow as opposed to deep comparison.
int arr1[] = { 1, 2, 3 };
int arr2[] = { 1, 2, 3 };
if (Arrays.equals(arr1, arr2)){
System.out.println("Same");
}
else {
System.out.println("Not same");
}
Same
Deep Equality
All of the methods you just saw are examples of regular equality. Whereas regular equality methods such as the .equals method compares the content of the objects themselves to check if they are equal (i.e. point to the same object), deep equality methods such as the .deepequals method compares the content of nested objects or arrays to determine equality.
import java.util.Arrays;
public class DeepEquality {
public static void main(String[] args) {
String[][] fruit1 = {
{"apple", "banana"},
{"orange", "grape"}
};
String[][] fruit2 = {
{"apple", "banana"},
{"orange", "grape"}
};
// Regular comparison (compares array references, not contents)
System.out.println("Regular/shallow equality result: " + (fruit1.equals(fruit2))); // will output false since the arrays do not reference the same object
// Deep comparison (compares array contents, not just references)
System.out.println("Deep equality result: " + (Arrays.deepEquals(fruit1, fruit2))); // will output true since the arrays have the same content
}
}
DeepEquality.main(null);
Regular/shallow equality result: false
Deep equality result: true
Challenge!
Identify the issue(s) in the code below (hint: try running it yourself). Then, make the necessary corrections to ensure that the program runs as intended.
public class Challenge {
private static boolean isName = false;
private static String name = new String("John");
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
System.out.println("Guess my name!");
String guess = sc.nextLine();
System.out.println("Your guess: "+guess);
if(guess == name){
isName = true;
} else {
System.out.println("Wrong! L Cope");
}
System.out.println(isName);
}
}
Challenge.main(null);
Guess my name!
Your guess: John
Wrong! L Cope
false
Data Tables!
Truth tables are used to easily describe boolean algebra operations. Boolean algebra is an branch of mathematics dealing with, rather than the vast stretches of integers, two digits: 1 and 0 (or true
and false
).
There are many different types of boolean operations, and we’ll be covering them all here. We also have an interactive quiz that allows you to see how good you are at this!
NOT (and states).
Boolean states
As you may know, binary and boolean states are very simple, 1 and 0, true and false. Boolean operations occur based off the comparison of two binary values, or inversion. Thus, these two boolean states are imperative to understanding. 1 and 0 are inverses, like on to off. They are also mutually exclusive. You can’t have a state that’s both on and off at the same time!
NOT
The NOT operator inverses whatever it is affecting.
The most basic operation is one that does
Question: What NOT(true)
Operation(s): AND
AND
AND is a boolean operation that you see in your everyday life! And in english is a conjugation, which denotes a combination of two or more objects, and in programming and binary math, it is very similar.
For Example, in English you’d say:
Take this and that
and you would not be fulfilling the request unless both this
and that
were taken.
Similarly, in Binary math, when you use the and operator, you are only considering the output true unless both are true.
AND: (XY)
python: True and False
javascript: true && false
java: true && false
X | Y | Output |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
NAND
NAND is the not operator for and. In other words, it is the complete inverse of the AND function.
In english this would be: DON'T take this and that
. Note how the DON'T
is a negative, asking you not to take both, but to take either.
In binary this would be:
NAND: (XY)’ (The '
denotes inverse)
python: not (True and False)
javascript: !(true && false)
java: !(true && false)
X | Y | Output |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | TRUE |
Inhibition
Inhibition is a pseudo-and (not actual jargon) function. Written in plain-text, the Inhibition function can be two things: X·NOT(Y) or NOT(X)·Y. It is when one input is True, but the other is False. This is the inverse of either X or Y, but not both. It can be written as X or Y Inhibition.
Inbiting X: (X’Y)
python: (Not X)&Y
javascript: !(X)&&Y
java: !(X)&&Y
X | Y | Output |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | FALSE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
Inbiting Y: (XY’)
python: X&(Not Y)
javascript: X&&!(Y)
java: X&&!(Y)
X | Y | Output |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
Note how the first and second terms (in their respective inhibitions) are inverted.
Question: What would 1(0) be? What about (1)(0)’? What about true&&false?
Operation(s): OR
AND operations require both arguments in the function to be true in order to return true. However, or operations only require one to be true to return true. OR gates being more forgiving makes them great to check for different cases that AND simply cannot take. However, there are many variations that allow for greater specificity.
OR
English Example: Take either this or that
. Here, if you take this
, you fulfill the request. But if you also took that
, you would also fulfill the request. In fact, if you took both, you’d actually be fulfilling the request, because they didn’t specify to not take both.
Translated to binary, this is:
OR: (X + Y)
python: True or False
javascript: true || false
java: true || false
X | Y | Output |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
NOR
Remember NAND? This is NAND, but for or. It takes the complete output of OR, and takes the inverse of it.
NOR: (X + Y)’
python: not (True or False)
javascript: !(true || false)
java: !(true || false)
X | Y | Output |
---|---|---|
TRUE | TRUE | False |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | True |
**Question: What would 1+0 be? What about !(true | false)** |
XOR
XOR, eXclusive OR, or bitwise OR allows for a coder to only return true if specifically only one input is true, but the other input is false. For example, this would be a situation where, if you have two objects, you can only take one or the other, not both, and not none.
XOR: (X^Y)
python: True^False
javascript: true^false
java: true^false
X | Y | Output |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
XNOR
XNOR is the Exclusive NOR. This is the direct inverse of the XOR function, so it would be pretty simple.
XNOR: (X^Y)’
python: not (True^False)
javascript: !(true^false)
java: !(true^false)
X | Y | Output |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | TRUE |
Question: what would true^false be? what would !(false^false) be?
PEMDASNAO
- Parenthesis
- Exponents
- Mutliplication/Divsion
- Addition/Subtraction
- NOT
- AND
- OR IN THIS ORDER
De Morgan’s Law
Above is an image of the important boolean algebra laws that are necessary to know. Not memorize, but know. The most important one we will cover is De Morgan’s law. Mainly because it is the most complex. As per wikipedia:
The rules can be expressed in English as:
- The negation of a disjunction is the conjunction of the negations
- The negation of a conjunction is the disjunction of the negations
Notice how it the conjunction references AND and disjunction represents OR. Thus, this can be restated as…
- NOT (A OR B) is equivalent to (NOT A) AND (NOT B)
- NOT (A AND B) is equivalent to (NOT A) OR (NOT B)
This is very useful when evaluating boolean expressions.
Your Homework
Now that you know what boolean expressions are and how to write them, as well as several comparison methods, your task is to write a class that uses either the compareTo or comparator and compare. Then create two instances of these classes and demonstrate using if statements.
BONUS: Create a program that checks if a year is a leap year or not.
Here is how the method should work:
(1) Prompt the user to input any year that they would like
(2) Determine if the year is a leap year or not
(3) Print the necessary dialogue (ex. [year] is/is not a leap year) AND return the value of any boolean(s) used
also…
Complete the weird questions below.
Weird questions
- !(true)&&(false) = ? what in boolean values?
- not ((((true and not (false)) ^ false) ^ true) && false) (remember PEMDASNAO!)
- 420 && 66 (Hint, convert to binary, then perform the operation)
- If you got this one, try 89 OR 42
For each example, you can use code, but then show your work and how you got it. Please ask questions if you are confused!