AP CSA Unit 2 Day 1: Boolean Expressions
Share
Boolean Expressions
Section 2.1 — Boolean Expressions
Key Concept
Boolean expressions evaluate to either true or false and form the foundation of all decision-making in Java. Relational operators (==, !=, <, >, <=, >=) compare two values and produce a boolean result. A common mistake is confusing the assignment operator (=) with the equality operator (==). In Java, if (x = 5) is a compile error (unlike C/C++), because assignment produces an int, not a boolean.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) true true false
x > y: 10 > 5 is true. x == 10: 10 == 10 is true. y != 5: 5 != 5 is false.
Why Not the Others?
(B) y != 5 is false because y is exactly 5.
(C) x == 10 is true because x is 10.
(D) x > y is true because 10 is greater than 5.
Common Mistake
The != operator means "not equal to." If the values ARE equal, the expression evaluates to false.
AP Exam Tip
Evaluate each boolean expression independently before combining results. Write T or F next to each one.