Concepts / Boolean Expressions in Java

Boolean Expressions in Java

Boolean operators form complicated conditions from boolean values.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

A Decision That Depends on Two Questions

Programs often need to make a decision that depends on more than one fact. A program might need to check that a number is not zero and that a related calculation gives a certain result. In English we combine such conditions with the words and, or, and not. Java provides boolean operators for the same purpose. These operators combine or change boolean values so that a program can make a decision using more than one condition.

What do you think happens?

Suppose x is 0. In the expression x != 0 && y / x > 1, will Java evaluate the part y / x > 1 at all?

  • Yes, Java always evaluates both sides of &&

  • No, Java stops after the left side because the whole expression can no longer be true

Reveal answer
Answer:

No, Java stops after the left side because the whole expression can no longer be true

The && operator uses short-circuit evaluation, so the second operand may not be evaluated. Once the left operand is false, the complete && expression must be false, so the right operand is skipped. This matters here because dividing by zero is an invalid operation.

Combining Boolean Values with && and ||

Definition

Boolean operators form complicated conditions from boolean values. The && operator combines two operands, and the result is true only when both operands are true. The || operator combines two operands, and the result is true when at least one operand is true.

Key point

Use && when both conditions must be true. Use || when at least one condition may be true. Read a compound expression from left to right, evaluating each operand to true or false before combining them.

Worked example

Evaluating a && expression with two different values of x

Evaluate x != 0 && y / x > 1 when y is 10, first with x equal to 5 and then with x equal to 0.

  1. 1
    Step 1: Evaluate the left operand when x is 5

    The question x != 0 asks whether x is not zero. Since 5 is not zero, the left operand is true.

  2. 2
    Step 2: Evaluate the right operand when x is 5

    Because the left operand is true, the right operand must be checked. y / x is 10 / 5, which is 2. Since 2 is greater than 1, the right operand is true.

  3. 3
    Step 3: Combine the results when x is 5

    With &&, the complete result is true only if both operands are true. Both are true, so the whole expression is true.

  4. 4
    Step 4: Evaluate the left operand when x is 0

    Now x is 0, so x != 0 is false. The left operand is false.

  5. 5
    Step 5: Decide whether the right operand is needed

    A && expression can be true only if both operands are true. Since the left operand is already false, the complete result is false, and the right operand does not need to be evaluated.

Result

With x equal to 5, the expression is true. With x equal to 0, the expression is false, and y / x is never computed.

Tracing Short-Circuit Evaluation

The rule behind the last worked example is called short-circuit evaluation. Both && and || use it. The second operand may not be evaluated at all, depending on the value of the first operand. For &&, a false left operand settles the answer as false. For ||, a true left operand settles the answer as true. In both cases Java can skip the right operand. This is useful when the right operand would be unnecessary, or when evaluating it would be invalid, such as dividing by zero.

Evaluate x != 0x is 0, so falseRight operand skippedy / x > 1 is not evaluatedResult false&& cannot be trueEvaluate y / x > 1only when x is not zeroResult from rightsidetrue or falsefalsetrue
When the left operand of && is false, the right operand is skipped and the expression is false. Which path does the program take when x is 0?

The diagram shows the same reasoning as the worked example. The left operand is checked first. Only when it is true does the program move on to the right operand. The right operand is therefore protected by the left one. This is the main reason the order of operands in a && expression matters: a guard condition should appear on the left.

java
Output
Guarded: x is zero, so the division was skipped
Notes on the code
  • x != 0 is the guard. It is on the left, so it is evaluated first.
  • Because the guard is false, y / x is never executed and no division by zero occurs.

Reversing a Value with the ! Operator

The ! operator reverses the value of a boolean. A true value becomes false, and a false value becomes true. Unlike && and ||, ! does not combine two boolean values. It changes one boolean value. This makes ! useful when a program needs the opposite of a condition, such as checking that a task is not done.

Before
boolean done = false;
boolean ready = done;

done is false, so ready is false

After
boolean done = false;
boolean ready = !done;

done is false, so !done is true and ready is true

When ! is applied to a longer expression, the whole expression is evaluated first and its result is reversed. For example, !(x > 3) is true exactly when x > 3 is false. Parentheses make clear which part the ! applies to.

Finding the Part That Caused a Result

A compound condition can be read as a tree. Each operator combines the values of its operands, and each operand may itself be a smaller expression. To find out why a long condition produced a result, trace the values from the leaves upward. Consider the condition (a > 0 && b < 5) || !done. Suppose a is 3, b is 7, and done is false. The comparison a > 0 is true, and b < 5 is false. The && combines these into false. Then !done is true, because done is false. Finally, the || combines false with true, so the whole condition is true. The part that produced the final true result is !done, not the && part.

||true&&falsea > 03 > 0 is true!donetrueb < 57 < 5 is falsedonefalseleftrightleftright
Each sub-expression has a value that feeds into the operator above it. With a = 3, b = 7, and done = false, which sub-expression produces the final true result?

Comparing the Truth Outcomes of && and ||

Left operandRight operanda && ba || b
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

Results of && and || for every combination of two boolean operands. Ignore short-circuiting here: the table shows the final value only.

The table shows the rule in one place. The && result is true only in the first row. The || result is false only in the last row. Short-circuit evaluation does not change these final values; it only decides whether the right operand must be computed to reach them.

Mistakes Beginners Make with Compound Conditions

  • Common mistake

    Using && when at least one condition is enough

    What it looks like
    if (isMember && hasCoupon) when the coupon alone should be enough
    Why it fails

    && requires both operands to be true, so the condition is stricter than intended.

    Do this instead

    Use || when at least one condition may be true.

  • Common mistake

    Placing an unsafe operation before its guard

    What it looks like
    y / x > 1 && x != 0 when x can be 0
    Why it fails

    The left operand is evaluated first, so the division runs before the guard can prevent it.

    Do this instead

    Place the guard on the left: x != 0 && y / x > 1.

  • Common mistake

    Assuming both operands always run

    What it looks like

    Expecting a method call on the right side of || to run even when the left side is true

    Why it fails

    Short-circuit evaluation may skip the right operand entirely.

    Do this instead

    Do not put side effects or required actions in an operand that may be skipped.

  • Common mistake

    Applying ! to the wrong part of an expression

    What it looks like
    !x > 3 when you meant !(x > 3)
    Why it fails

    The ! operator changes one boolean value, and without parentheses it may apply only to the nearest operand.

    Do this instead

    Use parentheses to show exactly which boolean value is reversed.

Practice Tracing a Compound Condition

MEDIUM

Given int x = 0, int y = 8, and boolean flag = true, decide whether the expression x != 0 && y / x > 1 || flag is true or false. Then decide whether the division y / x is evaluated, and explain why. Finally, rewrite the expression with the guard placed so that the division is never evaluated when x is zero.

Hints
  • Start with the left operand of && and decide whether it is true or false.
  • A false left operand of && settles that part of the expression without evaluating the right operand.
  • Remember that || is true when at least one of its operands is true.

Key Takeaways

  • Java boolean operators combine or change boolean values, so a program can decide using several conditions at once.
  • && is true only when both operands are true, and || is true when at least one operand is true.
  • Short-circuit evaluation means the right operand of && or || may be skipped, so a guard condition should be placed on the left.
  • The ! operator reverses one boolean value: true becomes false and false becomes true.
  • To locate the cause of an unexpected result, evaluate each leaf of a compound condition and work upward through its operators.