Concepts / Conditional Statements in Java

Conditional Statements 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…

Why Decisions Need More Than One Test

A program often has to make a decision that depends on more than one fact. In English we use the words and, or, and not to express such conditions. For example, we might only go outside if it is not raining and we have finished our work. Java provides boolean operators for the same purpose. These operators combine or change boolean values so that a program can make decisions using more than one condition.

This article covers the three boolean operators you need for compound conditions: && (both must be true), || (at least one may be true), and ! (reverse a value). It also covers short-circuit evaluation, which decides how much of a condition Java actually runs. That detail matters more than it first appears, because it can prevent an error from happening at all.

Predicting a Guarded Division

Before reading the mechanism, try to predict what a program does when a division could be invalid. Consider a condition that first checks whether x is not zero and then checks whether y divided by x is greater than 1. Keep the question below in mind as you read the rest of the article.

What do you think happens?

If x is 0 and y is 10, what does the condition x != 0 && y / x > 1 do?

  • It divides 10 by 0, which fails, and the program stops with an error

  • It evaluates to false, and the division y / x is never performed

  • It evaluates to true because y is greater than x

Reveal answer
Answer:

It evaluates to false, and the division y / x is never performed.

The left operand x != 0 is false. Because && is true only when both operands are true, the result is already known to be false. Java uses short-circuit evaluation, so it does not evaluate the right operand, and the division by zero never happens.

Following the Guard Step by Step

Read a compound condition from left to right. In the source example, the first operand asks whether x is not zero. The second operand asks whether y divided by x is greater than 1. Because the expression uses &&, the complete result can be true only if both operands are true. The diagram traces what happens when x is 0.

x != 0 ?falsesecond operand skippedFinal resulttrue or false from y / x >1y / x > 1runs only when x is not 0no, x is 0yesdecides the result
When x is 0, which operand runs and which one is skipped in x != 0 && y / x > 1?

The path shows the key idea of short-circuit evaluation. The source notes that && and || use short-circuit evaluation, so the second operand may not be evaluated. When x is 0, the left operand is already false, so the right operand cannot change the outcome of &&. Java skips it. This protects the program, because y / x would be invalid when x is 0.

java
Output
Guard blocked the division
Notes on the code
  • x != 0 is false, so the && expression is already false
  • y / x is skipped by short-circuit evaluation, so no division by zero occurs
  • The else branch runs because the whole condition is false

Building Conditions with && and ||

Java's && and || operators take two boolean values and produce one boolean result. The result depends only on the values of the operands. The two operators answer different questions. The table and diagram below show every combination of two operands.

ABA && BA || B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

Results of && and || for every combination of two boolean operands

A true, B truetrueA true, B truetrueA true, B falsefalseA true, B falsetrueA false, B truefalseA false, B truetrueA false, B falsefalseA false, B falsefalse
For each combination of true and false operands, what does && produce and what does || produce?

The && operator gives true only when both operands are true. Use it when both conditions must hold. The || operator gives true when at least one operand is true, so it fits cases where either condition is enough. Only the case where both operands are false makes || false.

Formula, step by step
A && B is true only when A is true and B is true
  1. 1
    Evaluate A from left to right; if A is false, the result is false and B is not evaluated
  2. 2
    If A is true, evaluate B
  3. 3
    The result is true only when both A and B are true
Worked example

Deciding whether a value falls in a range

Given int score = 75, decide whether score is at least 50 and at most 80 using &&.

  1. 1
    Write the two conditions

    score >= 50 is true for 75, and score <= 80 is true for 75.

  2. 2
    Combine with &&

    The condition is score >= 50 && score <= 80, which needs both parts to be true.

  3. 3
    Evaluate left to right

    The left operand is true, so Java also evaluates the right operand, which is true.

  4. 4
    Apply the && rule

    true && true is true, so the whole condition is true.

Result

The condition is true, so 75 lies in the range from 50 to 80.

Reversing a Value with the ! Operator

The ! operator reverses a boolean value. 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 it useful for asking the opposite of a condition, such as whether a flag is not set.

java
Output
false
true
false
Notes on the code
  • !test turns true into false
  • !(a && b) first computes a && b, which is false, then reverses it to true
  • !a && b applies ! only to a, so it computes false && false, which is false
Before
boolean result = a && b;

With a true and b false, a && b is false

After
boolean result = !(a && b);

With the same values, !(a && b) is true

Finding the Culprit in a Compound Condition

When a compound condition gives an unexpected result, do not look at the whole expression at once. Split it into its parts and find the sub-result of each part. The tree below uses the expression (a && b) || !c with a true, b false, and c false. Each leaf is a single condition, and each internal node combines the results below it.

||true&&falseatrue!truebfalsecfalseleftrightleftrightnegated
In (a && b) || !c, how do the sub-results combine upward, and which leaf condition is responsible for the final true?
Code walkthrough
boolean a = true;
boolean b = false;
boolean c = false;
boolean result = (a && b) || !c;
System.out.println(result);
  1. 1
    a && b is true only if both are true; b is false, so this sub-result is false
  2. 2
    !c reverses c; c is false, so this sub-result is true
  3. 3
    The || combines false and true; one true operand is enough, so the result is true
  4. 4
    The leaf responsible for the final true is !c, because the left side contributes false
Output
true

This method works for any compound condition. Evaluate each innermost piece, then combine the results upward using the rules for &&, ||, and !. The part whose sub-result decides the final outcome is the one to inspect when the answer surprises you.

Mistakes Beginners Make with Compound Conditions

  • Common mistake

    Assuming both operands of && are always evaluated

    What it looks like
    if (x != 0 && y / x > 1) with x equal to 0
    Why it fails

    Short-circuit evaluation can skip the second operand when the first operand already decides the result.

    Do this instead

    Place the guard test on the left and rely on Java skipping the risky test when the guard is false.

  • Common mistake

    Using && when at least one condition is enough

    What it looks like

    Requiring both a discount code and a member flag when either one should qualify

    Why it fails

    && is true only when both operands are true, which is stricter than the case described.

    Do this instead

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

  • Common mistake

    Reversing only part of an expression by accident

    What it looks like

    !a && b when the intent was !(a && b); with a true and b false, the first gives false and the second gives true

    Why it fails

    Without parentheses, ! applies only to the operand immediately after it.

    Do this instead

    Add parentheses around the whole group you want to reverse, as in !(a && b).

  • Common mistake

    Treating ! as if it combines two boolean values, when it only changes one value

Trace It Yourself

EASY

Given boolean p = false; boolean q = true; boolean r = false;, determine the value of (p || q) && !r. Trace each sub-result before giving the final answer, and state which operand, if any, is skipped by short-circuit evaluation.

Hints
  • Start with the innermost part: p || q
  • Then compute !r on its own
  • In the final &&, check whether the left operand already decides the result

Key Takeaways

  • Java uses && when both conditions must be true and || when at least one condition may be true
  • Short-circuit evaluation means the second operand of && or || may not be evaluated, which can prevent an invalid operation such as division by zero
  • The ! operator reverses one boolean value: true becomes false and false becomes true
  • To find the cause of an unexpected result, evaluate the innermost sub-conditions first and combine them upward using the rules for &&, ||, and !