Logical Operators in Java – AND, OR and NOT with Examples
Logical operators combine or invert boolean conditions. They let a program make decisions such as "the user may enter if they are an adult and have an ID" or "show a discount if the customer is a member or has a coupon".
Java has three logical operators: && (AND), || (OR) and ! (NOT). This tutorial explains each one, shows truth tables, and covers short-circuit evaluation, the difference between && and &, De Morgan's laws and precedence.
1. The Three Logical Operators
| Operator | Name | Result is true when… | Example |
|---|---|---|---|
&& | Logical AND | both conditions are true | age >= 18 && hasId |
|| | Logical OR | at least one condition is true | isVip || age < 25 |
! | Logical NOT | the condition is false | !isVip |
public class LogicalBasics {
public static void main(String[] args) {
int age = 22;
boolean hasId = true;
boolean isVip = false;
boolean canEnter = age >= 18 && hasId; // AND: both must be true
boolean freeDrink = isVip || age < 25; // OR: at least one must be true
boolean mustPay = !isVip; // NOT: flips the value
System.out.println("canEnter = " + canEnter);
System.out.println("freeDrink = " + freeDrink);
System.out.println("mustPay = " + mustPay);
// Combining operators (use parentheses for clarity)
boolean discount = (age < 25 || isVip) && hasId;
System.out.println("discount = " + discount);
}
}
canEnter = true freeDrink = true mustPay = true discount = true
2. Truth Table
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| false | false | false | false | true |
| false | true | false | true | true |
| true | false | false | true | false |
| true | true | true | true | false |
Logical operators work only on boolean values. Unlike C, Java does not treat numbers as true or false, so if (count && total) does not compile when they are integers.
3. Short-Circuit Evaluation
&& and || evaluate the right operand only if it is needed:
- For
A && B, ifAisfalse, the result must befalse, soBis skipped. - For
A || B, ifAistrue, the result must betrue, soBis skipped.
public class ShortCircuit {
static boolean check(String name, boolean result) {
System.out.println(" evaluated " + name);
return result;
}
public static void main(String[] args) {
System.out.println("false && ...");
boolean a = check("left", false) && check("right", true); // right side skipped
System.out.println("result: " + a);
System.out.println("true || ...");
boolean b = check("left", true) || check("right", false); // right side skipped
System.out.println("result: " + b);
System.out.println("false & ... (no short-circuit)");
boolean c = check("left", false) & check("right", true); // both sides run
System.out.println("result: " + c);
// Practical use: a null check protects the method call
String input = null;
if (input != null && !input.isBlank()) {
System.out.println("Got input");
} else {
System.out.println("No input (and no NullPointerException)");
}
}
}
false && ... evaluated left result: false true || ... evaluated left result: true false & ... (no short-circuit) evaluated left evaluated right result: false No input (and no NullPointerException)
Short-circuiting is more than a speed-up: it lets the left condition guard the right one, as in the null check above. If the order were reversed (!input.isBlank() && input != null), the program would throw a NullPointerException.
4. && vs & and || vs |
| Feature | && / || | & / | |
|---|---|---|
| Operand types | boolean only | boolean or integers (bitwise) |
| Short-circuit | Yes | No: both sides are always evaluated |
| Typical use | Conditions in if and loops | Bit manipulation, or when both sides must run |
In conditions, almost always use && and ||. See Bitwise Operators for &, | and ^.
5. De Morgan's Laws, XOR and Precedence
public class ConditionRules {
public static void main(String[] args) {
boolean raining = true, haveUmbrella = false;
// De Morgan's laws: !(A && B) == !A || !B and !(A || B) == !A && !B
System.out.println("!(raining && haveUmbrella) = " + !(raining && haveUmbrella));
System.out.println("!raining || !haveUmbrella = " + (!raining || !haveUmbrella));
// XOR on booleans: true when exactly one is true
boolean cardPayment = true, cashPayment = false;
System.out.println("exactly one payment method: " + (cardPayment ^ cashPayment));
// && binds tighter than ||
boolean x = true || false && false; // true || (false && false)
boolean y = (true || false) && false;
System.out.println("true || false && false = " + x);
System.out.println("(true || false) && false = " + y);
// Range check
int score = 75;
System.out.println("score in 60..100: " + (score >= 60 && score <= 100));
}
}
!(raining && haveUmbrella) = true !raining || !haveUmbrella = true exactly one payment method: true true || false && false = true (true || false) && false = false score in 60..100: true
- De Morgan's laws:
!(A && B)equals!A || !B, and!(A || B)equals!A && !B. They help simplify negated conditions. - Exclusive OR:
^on booleans is true when exactly one side is true. - Precedence:
!binds tightest, then&&, then||. Relational operators such as>=are evaluated before all of them, soscore >= 60 && score <= 100needs no extra parentheses.
6. Writing Clear Conditions
- Give complex conditions a name:
boolean isEligible = age >= 18 && hasId;. - Put cheap or guarding checks first, so short-circuiting saves work and prevents errors.
- Use parentheses when mixing
&&and||. - Avoid double negatives:
if (isActive)is clearer thanif (!isInactive). - Do not compare booleans with
true: writeif (done), notif (done == true).
7. Summary
&&is true only if both sides are true;||is true if either side is true;!inverts.&&and||short-circuit, so the right side may not run.&,|and^also work on booleans but always evaluate both sides.- Precedence:
!>&&>||; use parentheses for clarity.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What are logical operators in Java?
Operators that combine or invert boolean values: && (AND), || (OR) and ! (NOT). They are used to build conditions for if statements and loops.
Q2. What is short-circuit evaluation?
When && or || can determine the result from the left operand alone, Java does not evaluate the right operand. false && x and true || x never evaluate x.
Q3. What is the difference between && and &?
&& works only on booleans and short-circuits. & always evaluates both operands and also works as a bitwise AND on integers.
Q4. What is the difference between || and |?
|| stops as soon as the left side is true; | always evaluates both sides. On integers, | is a bitwise OR.
Q5. Can logical operators be used with integers in Java?
No. &&, || and ! require boolean operands. Java does not convert numbers to booleans the way C does.
Q6. Which logical operator has the highest precedence?
! (NOT), followed by && (AND), then || (OR).
Q7. How do I avoid NullPointerException in conditions?
Put the null check first and join with &&: if (s != null && s.length() > 0). Short-circuiting skips the method call when s is null.
Q8. Is there a logical XOR operator in Java?
Yes, ^ works on booleans as logical XOR: it returns true when exactly one operand is true. There is no short-circuit version, because both sides are always needed.
Q9. What are De Morgan's laws?
!(A && B) is equivalent to !A || !B, and !(A || B) is equivalent to !A && !B. They are useful for rewriting and simplifying negated conditions.
Q10. What does true || false && false return?
true, because && binds tighter: it is evaluated as true || (false && false).
Q11. Should I write if (flag == true)?
No, just write if (flag), and if (!flag) for the opposite. Comparing with true is redundant and risks the typo if (flag = true).
Q12. When would I use the non-short-circuit & on booleans?
Rarely: only when both sides have side effects that must always happen, for example validating two form fields and reporting errors for both. Usually it is clearer to evaluate them in separate statements.
Q13. How do I check if a number is within a range?
Combine two comparisons with &&: if (x >= 1 && x <= 10). Java does not support chained comparisons like 1 <= x <= 10.
Q14. Are logical operators evaluated left to right?
Yes. The left operand is always evaluated first, and the right operand only if needed.
Q15. What is the result type of a logical expression?
Always boolean.
Q16. Can I use logical operators with Boolean objects?
Yes, Java unboxes them automatically. If a Boolean is null, unboxing throws NullPointerException; use Boolean.TRUE.equals(value) for null-safe checks.
Q17. How can I make complex conditions more readable?
Store parts in well-named boolean variables or extract them into methods such as isEligibleForDiscount(), and use parentheses when mixing AND and OR.
Q18. What does !! do in Java?
Applying ! twice returns the original boolean value. Unlike JavaScript, it is never needed in Java because values are already booleans.
Q19. Can short-circuiting skip important code?
Yes. If the right operand calls a method that must run (for example, logging or updating a counter), it may be skipped. Keep conditions free of side effects to avoid surprises.
Q20. Are logical operators used outside if statements?
Yes: in loop conditions, ternary expressions, return statements (return a && b;), stream filters and assignments to boolean variables.