Boolean Expressions and If Statements — AP Computer Science A CS A Study Guide
For: AP Computer Science A candidates sitting AP Computer Science A.
Covers: Boolean operators (
&&,||,!), short-circuit evaluation, compound conditions, De Morgan's laws, and equivalent boolean expressions, with exam-style practice and common mistake avoidance tips.You should already know: Basic Java or any other procedural-language programming.
A note on the practice questions: All worked questions in the "Practice Questions" section below are original problems written by us in the AP Computer Science A style for educational use. They are not reproductions of past College Board papers and may differ in wording, numerical values, or context. Use them to practise the technique; cross-check with official College Board mark schemes for grading conventions.
1. What Is Boolean Expressions and If Statements?
Boolean expressions are logical statements that evaluate to one of two values: true or false. When combined with if statements, they form the core of control flow in Java, allowing you to write code that makes dynamic decisions based on input or runtime conditions. This topic makes up 10-15% of the AP CS A exam, appearing in both multiple-choice questions and free-response questions (FRQs) across all units, from basic method logic to array processing and class implementation. Boolean logic aligns to Unit 3 of the official AP CS A Course and Exam Description (CED).
2. Boolean operators — &&, ||, !
Java uses three core boolean operators to combine or modify logical statements, ordered below from highest to lowest precedence:
- NOT (
!): A unary operator that flips the value of a boolean expression. If istrue, isfalse, and vice versa. - AND (
&&): A binary operator that returnstrueonly if both operands are true. The logical equivalent of in formal logic. - OR (
||): A binary operator that returnstrueif at least one operand is true. The logical equivalent of in formal logic.
The truth tables below summarize the behavior of each operator:
| T | T | F | T | T |
| T | F | F | F | T |
| F | T | T | F | T |
| F | F | T | F | F |
Worked Example
Given the variable definitions below:
int age = 17;
boolean isEnrolled = true;
Evaluate the following expressions:
!isEnrolled: Flipstruetofalse, returnsfalseage >= 13 && age <= 18: Both conditions are true, returnstrueage > 18 || isEnrolled: One condition is true, returnstrue
Exam tip: If you are unsure about operator precedence, use parentheses to explicitly group conditions — examiners will not penalize you for clear, explicit grouping, and it eliminates avoidable errors.
3. Short-circuit evaluation
The && and || operators use short-circuit evaluation: if the value of the first operand is sufficient to determine the final result of the expression, the second operand is never executed. This is a purpose-built feature to prevent common runtime errors:
- For
&&: If the first operand isfalse, the entire expression will always befalse, so the second operand is skipped. - For
||: If the first operand istrue, the entire expression will always betrue, so the second operand is skipped.
Worked Example
The code below checks if a number is non-zero and if 10 divided by the number is greater than 2:
int x = 0;
boolean valid = (x != 0 && 10 / x > 2);
If && did not short-circuit, the second operand 10 / x > 2 would execute when x=0, throwing an ArithmeticException for division by zero. Because x != 0 returns false, the second operand is skipped entirely, and valid is set to false with no error.
Exam tip: Examiners frequently test short-circuit behavior with null pointer checks: (str != null && str.length() > 5) is safe, because if str is null, the second operand (which would throw a NullPointerException) is never executed. If you reverse the order of the conditions, the code will crash when str is null.
4. Compound conditions
Compound conditions are boolean expressions that combine two or more simple conditions using the &&, ||, and ! operators to implement complex decision rules. They are used in if, while, and for statements to control when code blocks execute.
The biggest risk with compound conditions is unintended behavior due to operator precedence: && always evaluates before ||, so you must use parentheses to group conditions that should be evaluated together.
Worked Example
Suppose you want to implement a discount eligibility rule: Eligible if the customer is between 13 and 18 years old, OR is a college student and not a full-time employee.
Incorrect code (no grouping):
boolean eligible = age >=13 && age <=18 || isCollegeStudent && !isFullTime;
This evaluates as ((age >=13 && age <=18) || isCollegeStudent) && !isFullTime, which incorrectly excludes 17-year-old full-time employees, who should be eligible regardless of employment status.
Correct code (explicit grouping):
boolean eligible = (age >=13 && age <=18) || (isCollegeStudent && !isFullTime);
This matches the intended rule: the age group and student status conditions are evaluated separately, so 17-year-olds qualify even if they work full time.
5. De Morgan's laws
De Morgan's laws are two formal logic rules that define how the ! operator distributes over && and ||. They are the most frequently tested subtopic in this unit, used to simplify complex boolean expressions or rewrite them to equivalent, more readable forms.
The two laws are:
In plain language:
- The negation of "A and B" is equivalent to "not A or not B"
- The negation of "A or B" is equivalent to "not A and not B"
When applying De Morgan's laws to inequality conditions, remember to flip the direction of the inequality when adding the negation:
Worked Example
Simplify the expression !(testScore >= 60 && absences < 3) using De Morgan's laws:
- Distribute the negation across the
&&operator, swapping&&to|| - Negate each individual condition:
!(testScore >=60)becomestestScore <60, and!(absences <3)becomesabsences >=3 - Final simplified expression:
testScore < 60 || absences >=3
6. Equivalent expressions
Two boolean expressions are equivalent if they return the same true/false value for every possible set of input values. AP CS A multiple-choice questions frequently ask you to identify which of 5 options is equivalent to a given expression.
Common methods to prove or find equivalent expressions:
- Apply De Morgan's laws to rewrite negated compound conditions
- Use the commutative property: and
- Rewrite inequalities to equivalent forms (e.g. , )
- Test with edge values: Plug in boundary values (minimum, maximum, threshold values) for all variables to check if both expressions return the same result.
Worked Example
Which expression is equivalent to (height > 60 || hasParentalConsent)?
We can rewrite this using De Morgan's laws by adding a double negation:
Applying De Morgan's to the inner negation gives , so the equivalent expression is !(height <= 60 && !hasParentalConsent). Testing with edge values confirms equivalence: if height = 65, both original and rewritten expression return true; if height = 50 and hasParentalConsent = false, both return false.
7. Common Pitfalls (and how to avoid them)
- Pitfall 1: Using
=instead of==for equality checks: Writingif (x = 5)assigns 5 toxand always evaluates totruefor numeric values, leading to unintended behavior. Students make this mistake because they mix up assignment and equality syntax. Fix: Always use==for boolean comparisons, and read your conditions aloud to verify: "if x equals 5" instead of "if x is assigned 5". - Pitfall 2: Reversing the order of short-circuit conditions: Writing
(10 / x > 2 && x != 0)will throw a division by zero error whenx=0, because the division runs before the zero check. Students do this when they write conditions in the order they think of them, rather than ordering for safety. Fix: Always put null, zero, or out-of-bounds checks first in&&expressions. - Pitfall 3: Misapplying De Morgan's laws: Forgetting to flip individual condition operators when distributing negation, e.g. writing
!(x>3 && y<2)as!x>3 || !y<2which is syntactically and logically incorrect. Students rush through simplification and skip the step of negating each condition. Fix: Follow the two-step rule for De Morgan's: first flip each individual condition, then swap&&to||or vice versa. - Pitfall 4: Ignoring operator precedence for compound conditions: Skipping parentheses for grouped conditions leads to unintended evaluation order. Students assume
&&and||have equal precedence, like addition and subtraction. Fix: Use parentheses to explicitly group every set of related conditions, even if you think precedence will work correctly. - Pitfall 5: Using bitwise
&/|instead of logical&&/||: The bitwise operators do not short-circuit, so(x !=0 & 10/x >2)will throw a division by zero error whenx=0. Students confuse the two operator sets because they return the same logical result when both operands are evaluated. Fix: Only use&&and||for all boolean decision logic; reserve&/|for bitwise manipulation only.
8. Practice Questions (AP Computer Science A Style)
Question 1 (Multiple Choice)
Which of the following is equivalent to the boolean expression !( (score >= 70 && score < 90) || absent == true )?
A) (score < 70 || score >= 90) && absent == false
B) (score < 70 && score >= 90) || absent == false
C) !(score >= 70 && score < 90) && absent
D) (score < 70 || score >= 90) || absent == false
E) (score >= 70 || score < 90) && absent == false
Worked Solution: Apply De Morgan's law for negation of an OR expression first:
- A = (score >= 70 && score <90), so \neg A = !(score >=70 && score <90) = score <70 || score >=90
- , so
Combining these gives
(score <70 || score >=90) && absent == false, which matches Option A.
Question 2 (FRQ Logic)
Consider the code snippet below:
int a = 4;
int b = 9;
boolean result = (a > 2 || ++b < 10) && (b == 9);
What is the value of result after execution? Show your steps.
Worked Solution:
- Evaluate the left operand of the
&&operator first:(a > 2 || ++b < 10) a > 2evaluates totrue, so the||operator short-circuits, and++b < 10is never executed. The value ofbremains 9, and the left operand returnstrue.- Evaluate the right operand of the
&&operator:b ==9returnstrue(sincebwas never incremented). true && trueevaluates totrue, soresult = true.
Question 3 (Debugging)
A student wrote the following code to check if a customer is eligible for free shipping: Eligible if order total is at least $50 AND the customer is not using a restricted address.
boolean eligible = !(orderTotal < 50 || isRestrictedAddress);
Is the code logically equivalent to the intended rule? Justify your answer with De Morgan's laws.
Worked Solution:
Yes, the code is correct. Apply De Morgan's law to the student's expression:
, where and .
This simplifies to !(orderTotal <50) && !isRestrictedAddress, which is equivalent to orderTotal >=50 && !isRestrictedAddress — exactly the intended eligibility rule.
9. Quick Reference Cheatsheet
| Rule Type | Details |
|---|---|
| Boolean Operators | ! (NOT, highest precedence): flips boolean value&& (AND, medium precedence): true only if both operands true` |
| Short-Circuit Evaluation | && skips second operand if first is false` |
| De Morgan's Laws | Step 1: Flip each individual condition Step 2: Swap && and ` |
| Equivalent Expressions | , , Test equivalence with boundary values to verify |
| Syntax Rules | Use == for equality checks, not =Use parentheses to group compound conditions to avoid precedence errors |
10. What's Next
Boolean expressions and if statements are the foundational building block of all control flow in Java, so you will use them constantly across every remaining unit of the AP CS A syllabus. You will combine them with while and for loops (Unit 4) to repeat code blocks conditionally, with arrays and ArrayLists (Units 6 and 7) to filter and modify collections of data, with class methods (Unit 5) to validate input for instance variables, and with recursion (Unit 10) to define base cases that stop recursive execution. Mastery of this topic will not only help you answer the 10-15% of exam questions directly testing Boolean logic, but also eliminate avoidable bugs in FRQ code that cost you marks.
If you get stuck simplifying a boolean expression, identifying short-circuit behavior, or working through past paper questions, our AI tutor Ollie is available 24/7 to walk you through step-by-step solutions, highlight common traps, and generate custom practice problems tailored to your weak spots. Head to the homepage, to start practising for free right now, or explore our Unit 4 study guide on iteration next.