Boolean Logic

The Course
•
4 min read

Some decisions depend on more than one fact. && means both conditions must be true. || means at least one must be true. ! reverses a boolean value. These operators combine boolean expressions; a String or a number is not automatically accepted as a condition in Java.

Use parentheses to show which rules belong together. For example, a session is valid when its duration is at least 1 and at most 240. A value is invalid when it is below the minimum or above the maximum. Test the endpoints and a value outside each side. A single successful input cannot distinguish these rules.

The second expression may not run

Java short-circuits boolean combinations: in A && B, it does not evaluate B when A is false. In A || B, it does not evaluate B when A is already true. This matters when the second part would be unsafe or unnecessary. Do not substitute & or |: those are different operators, outside today’s practice.

Both ends of a valid range Java
public class Main {
    public static void main(String[] args) {
        int minutes = 25;
        boolean valid = minutes >= 1 && minutes <= 240;

        System.out.println(valid);
        System.out.println(!valid);
        System.out.println(minutes < 1 || minutes > 240);
    }
}
Check your prediction
true
false
false

The last expression describes invalidity directly. Test 0, 1, 240 and 241. The two invalidity expressions should agree for each of these integer inputs.

Guard a division Java
public class Main {
    public static void main(String[] args) {
        int total = 30;
        int count = 0;

        if (count != 0 && total / count >= 10) {
            System.out.println("Long average");
        } else {
            System.out.println("No long average");
        }
    }
}
Check your prediction
No long average

The left side is false, so total/count is not evaluated. Reverse the operands to see why the order protects this expression. Restore the safe order before continuing.

Make grouping visible Java
public class Main {
    public static void main(String[] args) {
        boolean hasTicket = true;
        boolean isGuest = false;
        boolean isOpen = false;

        System.out.println(hasTicket || isGuest && isOpen);
        System.out.println((hasTicket || isGuest) && isOpen);
    }
}
Check your prediction
true
false

&& binds more tightly than ||. In the first expression a ticket is sufficient even while closed. The second requires an open venue for either kind of admission. Choose the grouping that matches the actual rule.

Your turn

Exercise

Require both valid duration and availability

A session can be scheduled only if minutes is from 1 through 240 inclusive and hasTime is true. For minutes=25 and hasTime=false, print false. Test both endpoints with hasTime=true and test 0 and 241.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        int minutes = 25;
        boolean hasTime = false;
        // Combine all three conditions.
    }
}
Hint 1: the idea

All required facts must hold together. One valid endpoint does not cancel a missing availability fact.

Hint 2: a first step

First write the duration range, then require hasTime as another condition with &&.

Show one solution
public class Main {
    public static void main(String[] args) {
        int minutes = 25;
        boolean hasTime = false;
        boolean canSchedule = minutes >= 1 && minutes <= 240 && hasTime;

        System.out.println(canSchedule);
    }
}
false

Change it and explain

Make a truth table for isMember || hasPass using the four combinations of two booleans. Then add requiresOpen and explain exactly where the parentheses belong. Use concrete values to show why a careless grouping can admit someone while a venue is closed.

Keep side effects out of practice conditions: update a counter in its own statement rather than hiding the update inside an && expression. You will find it easier to predict values when a condition asks a question and the branch performs the change.

Was this article helpful?

Your response is saved on this device.