Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The boolean type and Boolean wrapper class

boolean is a primitive type with two values: true and false. It stores conditions and comparison results. Boolean is its wrapper class; a variable of this type can also hold null, which requires care when automatic unboxing occurs.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

boolean name = true;
Boolean boxed = Boolean.valueOf(false);

boolean is a primitive type and a reserved Java keyword. It has exactly two values: true and false. These two spellings are boolean literals, not keywords. The type describes conditions, such as the result of age >= 18. Numbers are not boolean values: if (1) is invalid, and you cannot cast int to boolean.

The ! operator negates a value. The && and || operators mean logical “and” and “or” respectively and use short-circuit evaluation: the right operand is evaluated only when needed to determine the result. Primitive boolean values can be compared using == and !=.

Boolean is a wrapper class in java.lang, not an alternative spelling of boolean. It can represent a boolean value as an object, for example in List<Boolean>; a primitive type cannot be a generic type argument. A Boolean variable can hold null. Java supports automatic boxing (boolean → Boolean) and unboxing (Boolean → boolean), but unboxing null throws NullPointerException. The expression Boolean.TRUE.equals(value) safely checks whether value represents true; it returns false for null.

Fields of type boolean and elements of boolean arrays default to false; fields of type Boolean default to null. A local variable must be assigned before it is read. The example demonstrates a condition, negation, boxing, and a null-safe check.

Examples

public class BooleanExample {
    public static void main(String[] args) {
        int age = 18;
        boolean hasTicket = true;
        boolean canEnter = age >= 18 && hasTicket;
        Boolean boxed = canEnter;
        Boolean missing = null;

        System.out.println(canEnter);
        System.out.println(!canEnter);
        System.out.println(boxed.booleanValue());
        System.out.println(Boolean.TRUE.equals(missing));
    }
}

Result

true
false
true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources