Java combines Boolean expressions with three logical operators: && (and) is true only when both sides are true, || (or) is true when at least one side is true, and ! (not) flips a value. Java applies ! first, then &&, then ||, and it stops evaluating && or || as soon as the left side settles the result, which lets you guard against errors such as dividing by zero.
Quick check
If int x = 4, what is the value of x > 2?Show answerHide answer
It is
true, because 4 is greater than 2.If int x = 4, what is the value of x != 4?Show answerHide answer
It is
false:!=means "not equal to", and 4 equals 4.Can "p and q" be true when q is false?Show answerHide answer
No. An "and" needs both parts to be true, so one
falsepart makes the whole thingfalse.
Know these already? Jump to the practice questions
What you'll be able to do
- Evaluate expressions that combine
&&,||and!for given values. - Complete a truth table for a compound Boolean expression.
- Apply Java's precedence order to decide which operator acts first.
- Explain how short-circuit evaluation skips the right-hand operand, and use it to guard a division or a String index.
Key terms
Logical operator
An operator that combines or flips boolean values: && (and), || (or) and ! (not).
- In plain English
- The joining words of a condition.
- Don't write
- "
||is false when both sides are true."
Truth table
A table with one row per combination of true and false inputs, giving the expression's value in each.
- In plain English
- Every possible case, checked one row at a time.
- Don't write
- "Two rows are enough to show an expression with two variables."
Short-circuit evaluation
Skipping the right-hand operand of && or || because the left-hand operand already decides the result.
- In plain English
- The right side is skipped once the left side settles the answer.
- Don't write
- "Java always evaluates both sides of
&&."
What do &&, || and ! do?
A compound Boolean expression joins two or more Boolean expressions with logical operators. For two boolean values a and b:
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 |
&& is true in one row only; || is false in one row only. Java's || is inclusive: it is true when both sides are true.
With int age = 15; and boolean member = true;, age >= 13 && age <= 19 is true, age < 12 || member is true, and !member is false. To test a range, repeat the variable on both sides: age > 0 && < 20 does not compile.
A truth table for n boolean inputs needs 2ⁿ rows, because each input doubles the number of cases. These operators are Java syntax, not on the Java Quick Reference: Learn this.
Check yourself
Show answerHide answer
a && b is false, because a is false; a || b is true, because b is true.
Which operator does Java apply first?
Java applies operators in precedence order, highest first:
| Order | Operators |
|---|---|
| 1 | ! |
| 2 | *, /, %, then +, - |
| 3 | <, >, <=, >= |
| 4 | ==, != |
| 5 | && |
| 6 | || |
So comparisons are worked out before && and || join them, and && groups before ||. With x = 1, y = -1 and z = -5, the expression x > 0 || y > 0 && z > 0 means x > 0 || (y > 0 && z > 0), which is true || false, so true. Reading it left to right as (x > 0 || y > 0) && z > 0 would wrongly give false.
! applies only to the operand next to it: !a && b means (!a) && b, not !(a && b). Parentheses override every rule, so add them whenever grouping matters.
Key idea
&& binds more tightly than ||, just as * binds more tightly than +.
Check yourself
Show answerHide answer
true. b && c is worked out first and gives false, then true || false is true.
What is short-circuit evaluation?
Java evaluates && and || from left to right, and skips the right-hand operand when the left one already decides:
false && anythingisfalse, so the right side is not evaluated.true || anythingistrue, so the right side is not evaluated.
This lets the left side act as a guard for an operation that would fail. Integer division by zero throws an ArithmeticException:
int count = 0;
int total = 50;
if (count != 0 && total / count > 10)
{
System.out.println("High average");
}
System.out.println("Checked");
count != 0 is false, so total / count never runs and the code prints only Checked. Swap the operands and the division runs first and throws, so the guard must come first.
Check yourself
Show answerHide answer
No. count == 0 is true, so || skips the division and the result is true.
How can a guard protect a String index?
substring(k, k + 1) returns the character at index k, but throws a StringIndexOutOfBoundsException when k is not a valid index. Checking k first prevents that:
String word = "cats";
int k = 4;
boolean endsS = k < word.length()
&& word.substring(k, k + 1).equals("s");
System.out.println(endsS);
"cats".length() is 4, so 4 < 4 is false, the substring call is skipped and the code prints false. With k = 3 the guard is true, substring(3, 4) is "s", and it prints true.
The guard needs <, not <=: the last valid index is length() - 1, so k <= word.length() lets 4 through and the call throws.
Check yourself
Show answerHide answer
It throws a StringIndexOutOfBoundsException, because substring(4, 5) now runs before the index is checked.
Worked example 1: Apply precedence to a mixed expression
Question: What is printed when this code segment runs?
int a = 3;
int b = 8;
boolean done = true;
boolean result = !done && a > 5 || b > 6;
System.out.println(result);
What tells you the method
One expression mixing !, && and ||, so group it by precedence before evaluating.
Step 1: Add the grouping Java uses.
((!done) && (a > 5)) || (b > 6).Why!comes first, comparisons next, then&&, and||last.Step 2: Evaluate the pieces.
Piece Value !donefalsea > 5falseb > 6truefalse && falsefalsefalse || truetrueWhy&&is worked out before||, so the&&row comes before the||row.
Check it
The wrong grouping !done && (a > 5 || b > 6) gives false && true, which is false, so precedence decides the output here.
Answer
true
Worked example 2: Design a condition with parentheses
Question: A ride admits riders at least 120 cm tall who are also at least 10 years old or with an adult. Design a method canRide(int height, int age, boolean withAdult) that returns whether a rider is admitted, then state what System.out.println(canRide(110, 12, true)); prints.
What tells you the method
"And" and "or" in one rule, so decide the grouping before writing the expression.
Step 1: Split the rule into conditions.
Height:
height >= 120. Age or adult:age >= 10 || withAdult.WhyEach part of the rule becomes one simple condition.
Step 2: Join them, with parentheses.
public static boolean canRide(int height, int age, boolean withAdult) { return height >= 120 && (age >= 10 || withAdult); }WhyWithout the parentheses,
&&groups first, so anyone with an adult would pass at any height.Step 3: Trace
canRide(110, 12, true).110 >= 120isfalse, so&&short-circuits and the method returnsfalse.WhyA
falseleft operand decides&&on its own.
Check it
Without the parentheses, the same call returns true, the wrong result. With them, canRide(130, 8, true) is true and canRide(130, 8, false) is false, as the rule says.
Answer
false
Worked example 3: Choose a safe condition
Question: count and total are int variables, and count is never negative. Which condition is true exactly when count is positive and total / count is greater than 70, and never throws an exception?
- A)
count > 0 && total / count > 70 - B)
total / count > 70 && count > 0 - C)
count >= 0 && total / count > 70 - D)
count > 0 || total / count > 70
What tells you the method
A possible division by zero, so look for a guard on the left of &&.
Step 1: Test each option with
countequal to 0.A:
0 > 0isfalse, so the division is skipped. B divides first and throws. C:0 >= 0istrue, so the division runs and throws. D:0 > 0isfalse, so||evaluates the division and throws.WhyZero is the only count that can cause an exception, so it rules out three options at once.
Step 2: Test A with a positive count.
With
count3 andtotal213,213 / 3is 71, and71 > 70istrue.WhyOnce the guard passes, the option must still give the right result.
Check it
With count 3 and total 210, A gives 70 > 70, which is false, but D gives true, because 3 > 0 alone settles ||.
Answer
A
Your turn
Question: What is printed when this code segment runs?
int x = 5;
int y = 0;
boolean p = x > 3 || 10 / y > 1;
boolean q = y != 0 && 10 / y > 1;
System.out.println(p + " " + q);
Step 1: Evaluate
p.x > 3istrue, so||skips10 / yandpistrue. No exception is thrown.Step 2: Your go: evaluate
q, then give the printed line.
Show the full solutionHide the solution
Step 2. y != 0 is false, so && skips 10 / y and q is false. The println joins the two values with a space.
Answer: true false
Traps
Trap
An expression with || is false when both sides are true.
It seems right because everyday "or" often means one or the other. But Java's || is true whenever at least one side is true, and that includes both.
What is true || true?
true.
Trap
The order of the two sides of && never matters.
It seems right because a && b and b && a have the same value when both sides can run. But Java may skip the right side, so only the guard-first order avoids a division by zero or a bad index.
With int n = 0, which of n != 0 && 6 / n > 1 and 6 / n > 1 && n != 0 throws an exception?
6 / n > 1 && n != 0 throws an ArithmeticException, because the division runs first.
Trap
0 < x < 10 tests whether x is between 0 and 10.
It seems right because that is how a range is written in math. But Java works out 0 < x first, giving a boolean, and a boolean can't be compared with 10, so the code does not compile. Write 0 < x && x < 10.
Rewrite 5 <= n <= 9 as a Java condition.
5 <= n && n <= 9.
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), multiple-choice questions ask you to evaluate compound conditions, pick the condition that matches a description, or spot which code avoids a run-time error by short-circuiting. In free response, the conditions in your own if statements and loops use these operators, so a wrong grouping or a missing guard changes what your method does.
Practice questions
- Recall In the expression
p || q && !r, which operator does Java apply first?
- A)
|| - B)
&& - C)
! - D) None: all three are applied from left to right.
Show answer
Answer: C. ! has the highest precedence of the three, so !r is worked out first, then &&, then ||.
Why the others are wrong:
- A reads the expression from left to right instead of by precedence.
- B knows that
&&comes before||but forgets that!comes first. - D treats the three operators as equal, but each has its own precedence level.
- Apply What is printed when this code segment runs?
int t = 12;
System.out.println(t > 10 && t < 20);
System.out.println(t < 0 || t % 2 == 0);
System.out.println(!(t == 12));
Show answer
Answer: true then true then false, one per line.
Marking points:
12 > 10and12 < 20are bothtrue, so the first line istrue.12 < 0isfalsebut12 % 2 == 0istrue, so the second line istrue.t == 12istrue, and!flips it, so the third line isfalse.
- Recall How many rows does a truth table need for an expression with three
booleanvariables?
Show answer
Answer: 8
Marking points:
- Each variable can be
trueorfalse, so there are 2 × 2 × 2 = 8 combinations.
- Exam-style Which numbered line throws an
ArithmeticExceptionwhen this code segment runs?
1: int n = 0;
2: boolean a = n == 0 || 8 / n > 1;
3: boolean b = n != 0 && 8 / n > 1;
4: boolean c = n >= 0 && 8 / n > 1;
5: boolean d = n > 0 || 8 % 2 == 0;
Show answer
Answer: Line 4.
Marking points:
- Line 2:
n == 0istrue, so||skips the division. - Line 3:
n != 0isfalse, so&&skips the division. - Line 4:
0 >= 0istrue, so8 / 0runs and throws. - Line 5: the right side is
8 % 2, which never divides byn.
- Exam-style
hasAtshould returntrueonly whenkis a valid index ofsand the character there equalsc, and it must never throw an exception. Precondition:k >= 0. Which expression completes it?
public static boolean hasAt(String s, int k, String c)
{
return /* expression */;
}
- A)
s.substring(k, k + 1).equals(c) && k < s.length() - B)
k < s.length() || s.substring(k, k + 1).equals(c) - C)
k <= s.length() && s.substring(k, k + 1).equals(c) - D)
k < s.length() && s.substring(k, k + 1).equals(c)
Show answer
Answer: D. The guard k < s.length() comes first, so for an invalid k it is false and && skips the substring call.
Why the others are wrong:
- A calls
substringbefore checkingk, sohasAt("tree", 4, "e")throws. - B uses
||, so any validkreturnstruewithout checking the character, and an invalidkreachessubstringand throws. - C uses
<=, an off-by-one guard:kequal tos.length()passes andsubstringthrows.
- Exam-style The method should return
truewhenvis from 1 to 100 inclusive. Give the number of the line that stops it working.
1: public static boolean inRange(int v)
2: {
3: boolean low = v >= 1;
4: boolean high = v <= 100;
5: return low || high;
6: }
Show answer
Answer: Line 5.
Marking points:
- Every
intis at least 1 or at most 100, solow || highis alwaystrue:inRange(500)returnstrue. - Both conditions must hold, so line 5 should be
return low && high;.
- Apply With
boolean p = false;andboolean q = true;, which expression istrue?
- A)
p && q - B)
!p && q - C)
!(p || q) - D)
!q || p
Show answer
Answer: B. !p is true and q is true, so && gives true.
Why the others are wrong:
- A needs both sides
true, butpisfalse. - C:
p || qistrue, and!flips the whole bracket tofalse. - D:
!qisfalseandpisfalse, so||givesfalse.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
&&needs both operandstrue;||needs at least one;!reverses one value.- Precedence runs
!, arithmetic, comparisons, then&&, then||; brackets override it. false && …andtrue || …skip the right operand.- Put the guard (a zero check or an index check) on the left so the risky operation runs only when it is safe.
- A truth table for n inputs has 2ⁿ rows.