THINK FIRST·CODE LATER

← Java Programming
Chapter 6 · Week 6

Selection and Boolean Logic

Before You Start: What You Must Be Able to Do

Before the questions, make sure you can: build a boolean expression with relational and logical operators and give its truth value; explain short-circuit evaluation and why it matters; apply De Morgan's laws to simplify a negated condition; predict which branch of a nested if/else runs, including when braces are omitted; compare characters and strings correctly; and write a switch statement, knowing which types it accepts and what happens when break is missing.

Boolean expressions

The relational operators <, <=, >, >=, == and != produce a boolean. They may be stored:

boolean isAdult   = (age >= 18);
boolean isTeenager = age >= 13 && age <= 19;   // no need for if

Writing if (isAdult == true) is redundant; write if (isAdult), and if (!isAdult) for the negation.

Logical operators and short-circuit evaluation

a b `a b` a || b !a
true true true true false
true false false true false
false true false true true
false false false false true

&& and || are short-circuit: if the left operand already decides the result, the right operand is never evaluated. This is not an optimisation detail — it is how you write safe guards:

if (count != 0 && total / count > 50)     // division never happens when count is 0
if (s != null && s.length() > 0)          // no NullPointerException

& and | also exist and always evaluate both sides; you rarely want them.

De Morgan's laws: !(a && b) is !a || !b, and !(a || b) is !a && !b. Negating x > 0 && x < 10 gives x <= 0 || x >= 10.

if, if/else, else if

if (mark >= 90)       grade = 'A';
else if (mark >= 80)  grade = 'B';
else if (mark >= 70)  grade = 'C';
else                  grade = 'F';

The ladder is tested top to bottom and stops at the first true condition, so the order of the tests is part of the logic. Reversing the ladder (testing mark >= 70 first) would give every student with 70 or more a C.

Two syntax traps:

if (x > 0);                    // stray semicolon: the if body is EMPTY
    System.out.println("positive");   // always runs

if (x > 0)
    System.out.println("a");
    System.out.println("b");   // NOT part of the if -- indentation is not a rule

Without braces, an if controls exactly one statement. An else always belongs to the nearest unmatched if (the dangling else rule); use braces to say what you mean.

Comparing values of different kinds

  • Numbers and char: use == and the relational operators.
  • Strings and other objects: use equals (or equalsIgnoreCase, compareTo); == compares references.
  • boolean: compare with == only when you must; usually just use the variable.
  • Never write if (x = 5) — that is an assignment. With int it does not compile, which is a mercy; with boolean variables it compiles and silently misbehaves.

The switch statement

switch (day) {                    // day may be byte, short, char, int, String or an enum
    case 1:
    case 7:  System.out.println("Weekend"); break;    // shared case labels
    case 2:  System.out.println("Monday");  break;
    default: System.out.println("Midweek");
}

Rules worth memorising: the selector may not be double, float, long or boolean; every case label must be a compile-time constant and must be unique; without break, execution falls through into the following cases; default is optional and may appear anywhere, but is conventionally last.

Use switch for equality against a small set of constant values, and an if ladder for ranges and compound conditions.

Remember
  • && and || stop as soon as the answer is known — put the guard on the left.
  • !(a && b) is !a || !b.
  • Without braces, if controls one statement only.
  • else binds to the nearest unmatched if.
  • A missing break makes a switch fall through.
  • Compare strings with equals.
Common Pitfalls
  • if (0 < x < 10) does not compile in Java; write x > 0 && x < 10.
  • A semicolon immediately after if (...).
  • An else if ladder whose conditions are in the wrong order.
  • Using == on strings and wondering why user input never matches.

Ready? Close the notes and practise.

38 questions. Predict the output before you check — that is the skill the exam measures.