← Back to course

Boolean Logic & if Statements

You’ll be able to

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.

Truth of && and ||
a && b : true only if both true · a || b : true if either true
`!a` reverses a. Short-circuiting means the right operand may be skipped once the result is settled.
Worked example

Trace this code: int x = 5; then if (x > 3 && x < 10) { System.out.println("A"); } else { System.out.println("B"); }

  1. 1.Evaluate the left condition x > 3: since x is 5, 5 > 3 is true.
  2. 2.Evaluate the right condition x < 10: 5 < 10 is true.
  3. 3.true && true is true, so the if block runs and the else is skipped.
Answer: It prints A, because 5 is greater than 3 and less than 10, making the combined condition true.
Checkpoint

What does this print? `int x = 5;` then `if (x > 3 && x < 10) { System.out.println("A"); } else { System.out.println("B"); }`

Watch out

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".

Checkpoint

What does this print? `int n = 8;` then `if (n % 2 == 0) { System.out.println("even"); } else { System.out.println("odd"); }`

On the exam

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