Unit 3: Boolean Expressions and If Statements – AP Computer Science A
🔑 Key Concepts
- Relational operators:
==
,!=
,<
,>
,<=
,>=
- Logical operators:
&&
,||
,!
if
,else if
, andelse
structures- Truth tables and short-circuit evaluation
- Nested conditionals and De Morgan’s Laws
🤔 Boolean Expressions
A boolean expression evaluates to either true
or false
.
int a = 5;
int b = 10;
System.out.println(a < b); // true
🧮 Relational and Logical Operators
Operator | Meaning | Example |
---|---|---|
== |
Equal to | x == 10 |
!= |
Not equal to | x != 5 |
> |
Greater than | x > 3 |
< |
Less than | x < 7 |
>= |
Greater than or equal | x >= 4 |
<= |
Less than or equal | x <= 2 |
&& |
Logical AND | x > 0 && x < 10 |
|| |
Logical OR | x < 0 || x > 100 |
! |
Logical NOT | !(x == 5) |
🔄 Control Structures
Basic if
statement:
if (score >= 90) {
System.out.println("A");
}
if-else
statement:
if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Non-negative");
}
if-else if-else
chain:
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("Below B");
}
🔁 Nested Conditionals
if (x > 0) {
if (x < 10) {
System.out.println("1 to 9");
}
}
🧠 De Morgan’s Laws
Original | Equivalent |
---|---|
!(A && B) |
!A || !B |
!(A || B) |
!A && !B |
These help simplify complex boolean logic.
🧪 Practice Multiple Choice (5 Questions)
1. What will this print?
int x = 5;
if (x > 0 && x < 10)
System.out.println("Yes");
else
System.out.println("No");
(A) Yes
(B) No
(C) YesNo
(D) Error
✅ Answer: (A)
2. Which of the following is true if x = 3
and y = 7
?
(A) x > y && y > 5
(B) x < y || x > 10
(C) !(x < y)
(D) x == y && y < 10
✅ Answer: (B)
3. Which statement checks if x
is between 1 and 100 (inclusive)?
(A) x >= 1 || x <= 100
(B) x > 1 && x < 100
(C) x >= 1 && x <= 100
(D) x <= 1 && x >= 100
✅ Answer: (C)
4. What is the output?
int a = 4;
int b = 4;
System.out.println(!(a != b));
(A) true
(B) false
(C) 0
(D) 4
✅ Answer: (A)
5. Which of the following expressions is equivalent to !(x < 5 || x > 10)
?
(A) x < 5 && x > 10
(B) x >= 5 && x <= 10
(C) x < 5 || x < 10
(D) x >= 5 || x <= 10
✅ Answer: (B)