Unit 2.2: Boolean Expressions
AP Computer Science A
Selection and Iteration
Learning Objectives
Develop code to create Boolean expressions with relational operators and determine the result of these expressions.
What are Boolean Expressions?
Definition
A Boolean expression is an expression that evaluates to either true or false.
Essential Knowledge 2.2.A.3
An expression involving relational operators evaluates to a Boolean value.
Examples of Boolean Values
Key Point: Boolean expressions are the foundation for making decisions in programming!
Equality Operators
Essential Knowledge 2.2.A.1
Values can be compared using the relational operators == and != to determine whether the values are the same.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | true |
| != | Not equal to | 5 != 3 | true |
Code Examples
Primitive vs Reference Types
Important Distinction!
Primitive types: == compares actual values
Reference types: == compares object references (memory addresses)
Primitive Types Example
Reference Types Example
Remember: For String comparison, use .equals() method for content comparison!
Numerical Comparison Operators
Essential Knowledge 2.2.A.2
Numeric values can be compared using the relational operators <, >, <=, and >= to determine the relationship between the values.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| < | Less than | 3 < 5 | true |
| > | Greater than | 8 > 3 | true |
| <= | Less than or equal | 5 <= 5 | true |
| >= | Greater than or equal | 7 >= 10 | false |
Practical Examples
Age Verification
Grade Evaluation
String Comparison
Common Mistakes to Avoid
❌ Mistake 1: Using = instead of ==
❌ Mistake 2: Using == with Strings
Practice Problems
Evaluate these Boolean expressions:
Answers:
1. true 2. true 3. true 4. true 5. false
String Practice:
Summary
Key Concepts Learned:
- Boolean expressions evaluate to true or false
- Equality operators: == and !=
- Comparison operators: <, >, <=, >=
- Difference between primitive and reference type comparisons
- Use .equals() for String content comparison
Remember for the AP Exam:
- Relational operators create Boolean expressions
- == compares values for primitives, references for objects
- Always use .equals() for String comparison
- Boolean expressions are essential for conditional statements