Unit 1 Cycle 1 Day 3: boolean Expressions and Type Behavior
Share
boolean Expressions and Type Behavior
Section 1.2 — Variables and Data Types
Key Concept
The boolean type in Java can only hold true or false. Unlike some other languages, Java does not treat integers as boolean values — if (1) is a compile error, not a truthy check. Boolean expressions are built using relational operators (==, !=, <, >, <=, >=) and logical operators (&&, ||, !). Understanding operator precedence is essential: ! binds tighter than &&, which binds tighter than ||.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) false
Trace the expression inside the parentheses:
x / y: 10 / 3 = 3 (integer division truncates the decimal).
3 > 3: evaluates to false because 3 is not greater than 3.
The boolean variable result stores false, which is what gets printed.
Why Not the Others?
(A) If the division were 10.0 / 3, the result would be approximately 3.33, and 3.33 > 3 would be true. But with integer division, 10 / 3 = 3, and 3 > 3 is false.
(C) Java does not print boolean values as 0 or 1. Unlike some other languages, Java prints true or false as words.
(D) The code compiles and runs correctly. A boolean variable can store the result of any comparison expression.
Common Mistake
The trap is integer division: 10 / 3 is 3, not 3.33. Since 3 > 3 is false (not greater, only equal), the result is false. If the question used >=, the answer would be true.
AP Exam Tip
Always perform the arithmetic first, then evaluate the comparison. Integer division often changes the result of boolean expressions. Write down intermediate values to avoid mistakes.