Unit 2 Cycle 1 Day 3: Boolean Variables as Conditions
Share
Boolean Variables as Conditions
Section 2.1 — Boolean Expressions
Key Concept
A boolean variable can be used directly as a condition without comparing it to true or false. Writing if (isDone) is preferred over if (isDone == true), and if (!isDone) is preferred over if (isDone == false). The AP exam tests your ability to read boolean variables as conditions and understand that a method returning boolean can be used directly in an if statement. Assigning the result of a relational expression to a boolean variable is also common: boolean passed = score >= 70;.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) GO MORE
isReady is true, so the first if executes, printing "GO ". isDone is false, so !isDone is true, and the second if executes, printing "MORE".
Why Not the Others?
(B) The second condition !isDone is true (since isDone is false), so "MORE" also prints.
(C) The first condition isReady is true, so "GO " also prints.
(D) Both conditions are true, so both print statements execute.
Common Mistake
The ! (NOT) operator flips a boolean: !false becomes true and !true becomes false. You do not need to write isReady == true; just isReady is sufficient.
AP Exam Tip
Boolean variables can be used directly as conditions without comparing to true or false. Writing if (flag) is preferred over if (flag == true).