Conditional Statements in Java
Boolean operators form complicated conditions from boolean values.
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
- Python evaluates the if condition first.
- If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
- If none is True, the else branch runs.
- 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.
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?
Reveal 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.
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.
Guard blocked the division- 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.
| A | B | A && B | A || B |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
Results of && and || for every combination of two boolean operands
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.
A && B is true only when A is true and B is true- 1Evaluate A from left to right; if A is false, the result is false and B is not evaluated
- 2If A is true, evaluate B
- 3The result is true only when both A and B are true
Deciding whether a value falls in a range
Given int score = 75, decide whether score is at least 50 and at most 80 using &&.
- 1Write the two conditions
score >= 50 is true for 75, and score <= 80 is true for 75.
- 2Combine with &&
The condition is score >= 50 && score <= 80, which needs both parts to be true.
- 3Evaluate left to right
The left operand is true, so Java also evaluates the right operand, which is true.
- 4Apply the && rule
true && true is true, so the whole condition is true.
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.
false
true
false- !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
boolean result = a && b;With a true and b false, a && b is false
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.
boolean a = true;
boolean b = false;
boolean c = false;
boolean result = (a && b) || !c;
System.out.println(result);- 1a && b is true only if both are true; b is false, so this sub-result is false
- 2!c reverses c; c is false, so this sub-result is true
- 3The || combines false and true; one true operand is enough, so the result is true
- 4The leaf responsible for the final true is !c, because the left side contributes false
trueThis 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 likeif (x != 0 && y / x > 1) with x equal to 0Why it failsShort-circuit evaluation can skip the second operand when the first operand already decides the result.
Do this insteadPlace 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 likeRequiring 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 insteadUse || 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 failsWithout parentheses, ! applies only to the operand immediately after it.
Do this insteadAdd 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
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 !