Boolean Logic & if Statements
- Evaluate boolean expressions using relational and logical operators
- Trace `if` / `else` statements to determine which branch runs
- Combine conditions with `&&`, `||`, and `!`
Boolean expressions
A boolean expression evaluates to true or false. Relational operators compare values: >, <, >=, <=, == (equal), and != (not equal). Note that == tests equality while a single = assigns. For int values, 5 == 5 is true and 5 != 5 is false. These expressions are the questions that conditionals ask.
if / else chooses a path
An if statement runs its block only when the condition is true; an attached else runs when it is false. Exactly one branch of an if/else executes. You can also test n % 2 == 0 to check whether n is even, since an even number leaves remainder 0 when divided by 2.
Combining conditions
Logical operators join booleans. && (and) is true only when both sides are true; || (or) is true when at least one side is true; ! (not) flips a boolean. So x > 3 && x < 10 is true only for values strictly between 3 and 10. Java uses short-circuit evaluation: with &&, if the left side is false it never checks the right.
Trace this code: int x = 5; then if (x > 3 && x < 10) { System.out.println("A"); } else { System.out.println("B"); }
- 1.Evaluate the left condition
x > 3: sincexis5,5 > 3istrue. - 2.Evaluate the right condition
x < 10:5 < 10istrue. - 3.
true && trueistrue, so theifblock runs and theelseis skipped.
A, because 5 is greater than 3 and less than 10, making the combined condition true.What does this print? `int x = 5;` then `if (x > 3 && x < 10) { System.out.println("A"); } else { System.out.println("B"); }`
Do not confuse = with ==. = assigns a value; == compares. Writing if (x = 5) is a common bug — for booleans it may even compile, but it means "assign", not "test".
What does this print? `int n = 8;` then `if (n % 2 == 0) { System.out.println("even"); } else { System.out.println("odd"); }`
The idiom x % 2 == 0 tests for even; x % 2 != 0 (or == 1 for positive x) tests for odd. Expect this pattern in tracing questions and in FRQ logic.
Answer the 2 checkpoints as you read.
Sign in to save your progress