Verified for the 2025 AP Computer Science A exam•Citation:
Using Boolean Expressions and If-Else If-Else statements, we can represent combinational logic and branching decisions. **
This unit introduces the idea of logic, especially when it comes to making decisions in code. We are introduced to boolean statements, which evaluate to a boolean value, either true or false. Using these, we can focus on branching, one of the building blocks of algorithms (the others are sequencing, which is going line by line, and iteration, which we will learn in unit 4). To achieve branching, we will learn If—Else If—Else statements.
Building Computational Thinking
Using boolean expressions with If-Else If-Else statements allows for the introduction of branching paths and choice to your programs, especially when you want the user to make a decision or when filtering out data. Using these, there are many ways that you can get the same result with the same logic, but we will focus on writing ones that are efficient.
These potential topics come from College Board:
Boolean expressions tell us whether something is true or false. There are the operators that can be used to create boolean expressions:
Conditional statements allow us to control the flow of our program by choosing to run code only if a certain condition is true.
some code before the if statement
if (number % 2 == 0) { if (number % 3 == 0) { return "Even and divisible by 3"; } else { return "Even"; } }
Boolean logic operators help us create compound boolean statements. These are the boolean logic operators:
There is an order of operations to these operators if there are multiple in one expression. The NOT operator has the highest precedence, followed by the AND operator and finally the OR operator.
Compound boolean statements combine several simple boolean expressions together.
some code before the if statement
if ((number % 2 == 0) && (number % 3 == 0)) { return "Even and divisible by 3"; } else if (number % 2 == 0) { return "Even"; }
Here is a truth table for a || !b && !a && !b. Since there is an order of operations to the boolean operators, we can rewrite this with parentheses as a || ((!b && !a) && !b).
a | b | !a | !b | !b && !a | (!b && !a) && !b | a || ((!b && !a) && !b) |
---|---|---|---|---|---|---|
False | False | True | True | True | True | True |
False | True | True | False | False | False | False |
True | False | False | True | False | False | True |
True | True | False | False | False | False | True |
Note that a || ((!b && !a) && !b)
is true whenever a
is true or b
is false, so we can rewrite a || ((!b && !a) && !b)
as a || !b
When comparing objects, you want to be careful.
String a = "Hi"; String b = new String("Hi"); System.out.println(a == b); // Prints false System.out.println(a.equals(b)); // Prints true