Java Booleans

Su Suriya Ravichandran Updated 14 Nov 2026
5 min read ·Lesson 14 of 133

A boolean holds one of exactly two values: true or false. Booleans drive every decision a program makes: every if, every loop condition, every filter. Java treats boolean as a distinct type that cannot be mixed with numbers, which removes a whole class of bugs common in C and JavaScript.

Declaring Booleans

boolean isLoggedIn = true;
boolean hasPermission = false;
boolean ready;          // field default is false; local must be assigned before use

true and false are literals, written in lowercase. True, TRUE, 1, and 0 are not boolean values in Java.

Boolean Expressions

Most booleans are not written as literals; they are the result of a comparison.

int age = 20;
int stock = 0;
String role = "admin";

boolean adult = age >= 18;              // true
boolean outOfStock = stock == 0;        // true
boolean isAdmin = role.equals("admin"); // true
boolean empty = role.isEmpty();         // false

Any expression using ==, !=, <, >, <=, >=, instanceof, or a method that returns boolean produces a boolean value. Storing the result in a well-named variable often makes later code read like a sentence:

boolean canCheckout = isLoggedIn && !outOfStock && cartTotal > 0;
if (canCheckout) {
    processOrder();
}

Combining Booleans

OperatorNameResult
a && bANDtrue only if both are true
a || bORtrue if at least one is true
!aNOTThe opposite of a
a ^ bXORtrue if exactly one is true

Truth table:

aba && ba || ba ^ b!a
truetruetruetruefalsefalse
truefalsefalsetruetruefalse
falsetruefalsetruetruetrue
falsefalsefalsefalsefalsetrue

&& and || short-circuit: the right side is evaluated only when it can change the result. This lets the left side act as a guard:

if (user != null && user.isActive()) { ... }      // isActive() never runs on null
if (cache.contains(key) || loadFromDisk(key)) { ... }  // disk read only on cache miss

De Morgan's laws

Negating a compound condition flips each part and swaps the operator:

!(a && b)  ==  !a || !b
!(a || b)  ==  !a && !b
// "not (valid and confirmed)" is "invalid or unconfirmed"
if (!(isValid && isConfirmed)) { ... }
if (!isValid || !isConfirmed) { ... }    // same meaning, often easier to read

Booleans Are Not Numbers

Java has no conversion between boolean and any numeric type:

boolean b = 1;           // compile error
int n = true;            // compile error
if (count) { }           // compile error when count is an int
if (name) { }            // compile error when name is a String

Conditions must be boolean expressions, so the intent has to be written out:

if (count != 0) { }
if (name != null && !name.isEmpty()) { }

This is why the C bug if (x = 5) (assignment instead of comparison) cannot happen with integers in Java: x = 5 has type int, which is not allowed as a condition. The one remaining form of this mistake is with boolean variables:

boolean done = false;
if (done = true) {       // compiles: assigns true, condition is always true
    finish();
}

Never compare a boolean to true or false. Write if (done) and if (!done). That is shorter and removes the possibility of the typo.

When a number is genuinely needed, convert explicitly:

int flag = done ? 1 : 0;
boolean fromInt = flag != 0;

The Boolean Wrapper Class

Boolean is the wrapper type, needed in collections and generics:

List<Boolean> answers = List.of(true, false, true);

boolean parsed = Boolean.parseBoolean("TRUE");    // true (case-insensitive)
boolean other = Boolean.parseBoolean("yes");      // false
String text = Boolean.toString(true);             // "true"
boolean both = Boolean.logicalAnd(true, false);   // false

parseBoolean returns true only for the text "true" in any letter case. Every other string, including "yes", "1", and null, returns false without throwing. When parsing user input or configuration, validate explicitly if values like "yes" should be accepted.

A Boolean variable can be null, unlike boolean. Unboxing null throws:

Map<String, Boolean> settings = new HashMap<>();
boolean darkMode = settings.get("darkMode");    // NullPointerException: key missing
boolean darkMode = settings.getOrDefault("darkMode", false);   // safe

Use the primitive boolean everywhere except where an object is required. A three-state value (yes, no, unknown) is better modeled as an enum than as a nullable Boolean.

Methods That Return Booleans

Methods answering yes-or-no questions conventionally start with is, has, can, or should, so call sites read naturally:

public class Account {
    private double balance;
    private boolean frozen;

    public boolean isFrozen() {
        return frozen;
    }

    public boolean canWithdraw(double amount) {
        return !frozen && amount > 0 && amount <= balance;
    }
}

canWithdraw returns the boolean expression directly. The longer form is redundant:

// Unnecessary
if (!frozen && amount > 0 && amount <= balance) {
    return true;
} else {
    return false;
}

The condition already is the answer; wrapping it in if/return true/return false adds lines without adding meaning.

Practical Example: Access Check

public class AccessControl {
    public static void main(String[] args) {
        String role = "editor";
        boolean emailVerified = true;
        boolean accountLocked = false;
        int failedLogins = 2;

        boolean isStaff = role.equals("admin") || role.equals("editor");
        boolean tooManyFailures = failedLogins >= 5;
        boolean canLogin = emailVerified && !accountLocked && !tooManyFailures;
        boolean canPublish = canLogin && isStaff;

        System.out.println("Can log in:  " + canLogin);
        System.out.println("Can publish: " + canPublish);
    }
}

Output:

Can log in:  true
Can publish: true

Each rule is a separate named boolean, so the final decisions read as plain statements of policy. Changing the lockout threshold or adding a role affects exactly one line. In larger applications the same pattern appears as permission-checking methods (user.canEdit(document)) that return a boolean composed from smaller checks.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining
Ask about this post
AI Ask about this post

Ask questions about Java Booleans and get answers drawn from it.

Signed-in readers only.