Java Boolean Values and Expressions

A Java boolean expression evaluates to true or false.

Lesson 9 of 127Beginner13 min read

A Java boolean expression evaluates to true or false. It can be a literal, a variable, a comparison or a combination of other boolean expressions. Conditions in if statements and loops must produce a boolean; Java does not treat an arbitrary number or nonempty string as automatically true.

The useful question is what decision the expression represents. A readable condition states that decision directly, such as whether a booking is available or whether an input falls inside an allowed range. Learn the truth rules and then test the boundaries that can change the answer.

Create conditions from comparisons

Relational comparisons such as quantity > 0 and temperature <= 30 produce booleans. Equality uses == and inequality uses !=. For primitives these operators compare values according to their type rules. For references, == compares identity; use equals when comparing string content.

Write the permitted boundary deliberately. age >= 18 includes eighteen, while age > 18 excludes it. This difference is small in syntax but significant in behavior. When a condition represents a range, test the smallest permitted value and values immediately outside that range. For two-sided ranges, combine separate comparisons rather than writing a chained mathematical comparison. Java expects both operands of && to be boolean expressions.

AND means both requirements must hold

The expression left && right is true only when both operands are true. It is false when either requirement fails. Use it for policies with simultaneous requirements, such as hasTicket && gateOpen. If a ticket is required and the gate must be open, using || instead would allow either condition to pass on its own.

Short-circuit evaluation means Java skips the right operand when the left is false. This can protect a method call or calculation, but the order must reflect the precondition. items != null && items.length > 0 is safe for a null array because the length check is skipped. The reversed order is not safe. Prefer conditions without unrelated state changes so that readers can understand them as questions rather than hidden actions.

OR means at least one requirement holds

The expression left || right is true when either operand is true, including when both are true. It is false only when both are false. Use OR for permitted alternatives, such as isMember || hasInvitation. Do not confuse inclusive OR with exclusive OR, where exactly one operand must be true; boolean ^ supplies exclusive OR when that is really needed.

Java skips the right operand of || when the left operand is true. For a condition with an expensive check, this can avoid unnecessary work, but correctness comes first. Do not reorder operands if a later operation needs an earlier precondition. A clearly named helper method can express a complicated alternative better than a long line containing several nested conditions.

NOT and grouping change the meaning

The ! operator reverses one boolean: !true is false and !false is true. Parentheses show the scope of the negation. !isClosed means the closed flag is false, while !(isClosed || isFull) means neither of those states is true.

De Morgan’s laws help explain equivalent expressions. !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Read these as logic rather than blindly rewriting punctuation. In a condition that rejects a booking when either prerequisite fails, !hasTicket || !gateOpen is a useful form. Avoid double-negative names such as notUnavailable if they make conditions harder to read. A positive name often removes an unnecessary mental reversal.

Store a decision or evaluate it directly

A boolean variable can give a meaningful name to a decision, such as boolean withinBudget = cost <= budget;. That variable stores the result computed at that moment. If cost changes afterward, withinBudget does not automatically update; recalculate it when the underlying information changes.

Use if (withinBudget) rather than if (withinBudget == true). Comparing to true adds no information. Likewise, use !withinBudget instead of comparing to false. For an input validation rule, a named boolean can make a later error message clearer. For a short condition used only once, evaluating directly inside if is often sufficient. Choose the arrangement that preserves the relationship between the data and the moment at which the decision is made.

Practice with explained solutions

Task 1. Write a rule allowing entry only if a visitor has a ticket and the door is unlocked.

Solution. Use hasTicket && !doorLocked. Both requirements must hold; an invitation-only alternative would need a separately defined rule.

Task 2. Rewrite !(isFull || isClosed) without placing NOT around a combined expression.

Solution. The equivalent form is !isFull && !isClosed. Both undesirable states must be absent, rather than merely one of them.

Java Summary

  • AND requires both conditions; inclusive OR permits either or both.
  • Use inclusive comparisons joined by AND for a closed range.
  • A stored boolean is a snapshot and does not recalculate when its inputs change.
  • Continue with if-else decisions.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Include both endpoints of a range

Save this complete program as RangeDecision.java. Compile with javac --release 17 RangeDecision.java and run with java RangeDecision.

Java
public class RangeDecision {
    public static void main(String[] args) {
        int score = 100;
        boolean valid = score >= 0 && score <= 100;
        System.out.println(valid);
        score = 101;
        System.out.println(score >= 0 && score <= 100);
    }
}
Output
true
false
Line-by-line explanation
  1. Lines 1 to 9The first result includes the upper boundary of one hundred. After score becomes one hundred and one, the upper comparison fails, so the combined expression is false. Try zero and negative one as well to inspect the lower boundary. This four-value test finds boundary mistakes that a single ordinary value such as fifty would not reveal.
Example 2

Observe the truth rules

Save this complete program as LogicalResults.java. Compile with javac --release 17 LogicalResults.java and run with java LogicalResults.

Java
public class LogicalResults {
    public static void main(String[] args) {
        boolean member = false;
        boolean invited = true;
        System.out.println(member && invited);
        System.out.println(member || invited);
        System.out.println(!invited);
    }
}
Output
false
true
false
Line-by-line explanation
  1. Lines 1 to 9AND fails because member is false. OR succeeds because invited is true even though member is false. NOT reverses the invitation flag. These are separate decisions, not three stages that change the variables: neither member nor invited is reassigned. The example isolates the operators so you can map each output to its truth rule.
Example 3

A stored result is a snapshot

Save this complete program as DecisionSnapshot.java. Compile with javac --release 17 DecisionSnapshot.java and run with java DecisionSnapshot.

Java
public class DecisionSnapshot {
    public static void main(String[] args) {
        int cost = 8;
        int budget = 10;
        boolean withinBudget = cost <= budget;
        cost = 12;
        System.out.println(withinBudget);
        System.out.println(cost <= budget);
    }
}
Output
true
false
Line-by-line explanation
  1. Lines 1 to 10withinBudget captures the result when cost is eight. Changing cost to twelve does not re-run the earlier expression, so that stored boolean remains true. The second println evaluates a fresh comparison and prints false. This distinction matters when a program updates quantities between validation and use: a named decision is readable but may become stale.

Common Java Mistakes

Using || in a range check

Replacing && with || in a range check usually accepts almost every number. For score >= 0 || score <= 100, a negative score still satisfies the second comparison, and a score above one hundred satisfies the first. Write a sentence describing the requirement: the score must be at least zero AND at most one hundred. Then verify values outside both boundaries.

Java FAQ

Can an int be used directly as an if condition?

No. Write a boolean comparison such as count != 0. Java keeps numeric and boolean types separate.

Is false the same as null?

No. false is a primitive boolean value. null is the absence of an object reference. A boxed Boolean can be null, which introduces additional unboxing risks.

How do I negate a combined condition correctly?

Use De Morgan's laws: !(a && b) is the same as !a || !b, and !(a || b) is the same as !a && !b. So "not between 0 and 100", !(score >= 0 && score <= 100), becomes score < 0 || score > 100. Negating each comparison without swapping the operator is a common mistake.

Should I write if (isReady == true)?

No. isReady is already a boolean, so write if (isReady) and if (!isReady). Comparing with true adds noise, and writing = by mistake, as in if (isReady = true), compiles and always runs the branch.

What does ^ do with booleans in Java?

^ is exclusive OR: it's true when exactly one side is true, so true ^ false is true and true ^ true is false. It's useful for "one or the other but not both" rules. Unlike && and ||, it always evaluates both sides.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Is score >= 0 || score <= 100 a valid closed-range test?

Multiple choicemedium

What is !(false || true)?

Java Quiz

2 questions to check what you learned.

  1. When is a && b true?

    • When both are true
    • When either is true
    • When both are false
  2. Which expression includes ages 18 through 65?

    • age >= 18 && age <= 65
    • age > 18 && age < 65
    • age >= 18 || age <= 65