Java Boolean Class Tutorial

In Java, the Boolean class is a wrapper class for the primitive boolean data type. It provides several methods and utilities to work with boolean values in object form. The Boolean class is part of the java.lang package, so you don't need to import it explicitly. It can be useful when you need to treat boolean values as objects, such as when working with collections or performing conversions between strings and boolean values.

In this tutorial, we'll cover:

1. Introduction to the Boolean Class

The Boolean class is part of Java's wrapper classes, which are used to convert primitive types into objects. This can be useful in cases where objects are needed, such as with Java Collections, or when methods require an object reference rather than a primitive type.

The Boolean class contains two constants:

Boolean.TRUE: Represents the true value of the boolean type.
Boolean.FALSE: Represents the false value of the boolean type.

2. Creating Boolean Objects

You can create a Boolean object in two ways:

Using the Boolean constructor.
Using Boolean.valueOf() (which is preferred as it provides better performance by reusing objects).

Example 1: Creating Boolean Objects

public class BooleanObjectExample {
    public static void main(String[] args) {
        // Creating Boolean objects using the constructor (not recommended)
        Boolean boolObj1 = new Boolean(true);
        Boolean boolObj2 = new Boolean("false");

        // Creating Boolean objects using Boolean.valueOf() (recommended)
        Boolean boolObj3 = Boolean.valueOf(true);
        Boolean boolObj4 = Boolean.valueOf("true");

        // Displaying values
        System.out.println("Boolean object 1: " + boolObj1);  // true
        System.out.println("Boolean object 2: " + boolObj2);  // false
        System.out.println("Boolean object 3: " + boolObj3);  // true
        System.out.println("Boolean object 4: " + boolObj4);  // true
    }
}

Explanation:

new Boolean(true) and new Boolean(“false”) create Boolean objects using the constructor (which is not recommended due to object creation overhead).
Boolean.valueOf() is preferred because it uses cached instances of Boolean.TRUE and Boolean.FALSE, avoiding unnecessary object creation.

3. Methods of the Boolean Class

The Boolean class provides several useful methods, including:

booleanValue(): Returns the value of the Boolean object as a primitive boolean.
toString(): Converts the Boolean object to its string representation (“true” or “false”).
parseBoolean(String s): Parses a string and returns a primitive boolean (true for “true” and false for any other value).
equals(Object obj): Checks whether two Boolean objects are equal.

Example 2: Using Boolean Methods

public class BooleanMethodsExample {
    public static void main(String[] args) {
        Boolean boolObj = Boolean.valueOf(true);

        // Using booleanValue() to get the primitive boolean
        boolean primitiveBool = boolObj.booleanValue();
        System.out.println("Primitive boolean value: " + primitiveBool);  // true

        // Using toString() to get the string representation
        String boolStr = boolObj.toString();
        System.out.println("String representation: " + boolStr);  // true

        // Using equals() to compare two Boolean objects
        Boolean anotherBool = Boolean.valueOf(true);
        System.out.println("Are both Booleans equal? " + boolObj.equals(anotherBool));  // true
    }
}

Explanation:

booleanValue() extracts the primitive boolean from the Boolean object.
toString() converts the Boolean object to its string representation.
equals() compares two Boolean objects for equality.

4. Auto-boxing and Unboxing with Boolean

Java automatically converts primitive types to their corresponding wrapper class (auto-boxing) and vice versa (unboxing).

This is done automatically by the Java compiler, which simplifies the code when working with primitive and object types.

Example 3: Auto-boxing and Unboxing with Boolean

public class AutoBoxingUnboxingExample {
    public static void main(String[] args) {
        // Auto-boxing: primitive boolean to Boolean object
        Boolean boolObj = true;  // Equivalent to Boolean.valueOf(true)

        // Unboxing: Boolean object to primitive boolean
        boolean primitiveBool = boolObj;  // Equivalent to boolObj.booleanValue()

        System.out.println("Auto-boxed Boolean: " + boolObj);
        System.out.println("Unboxed primitive boolean: " + primitiveBool);
    }
}

Explanation:

Auto-boxing: The primitive boolean is automatically converted to a Boolean object.
Unboxing: The Boolean object is automatically converted to a primitive boolean.

5. Comparing Boolean Values

The Boolean class provides methods for comparing boolean values, either in object form or as primitive values.

Example 4: Comparing Boolean Objects and Primitive Booleans

public class BooleanComparisonExample {
    public static void main(String[] args) {
        Boolean boolObj1 = Boolean.valueOf(true);
        Boolean boolObj2 = Boolean.valueOf(false);

        // Comparing Boolean objects
        System.out.println("boolObj1 equals boolObj2? " + boolObj1.equals(boolObj2));  // false

        // Comparing primitive booleans
        boolean primitiveBool1 = true;
        boolean primitiveBool2 = false;
        System.out.println("primitiveBool1 == primitiveBool2? " + (primitiveBool1 == primitiveBool2));  // false

        // Using Boolean compare() method
        System.out.println("Comparing true and false: " + Boolean.compare(primitiveBool1, primitiveBool2));  // 1
        System.out.println("Comparing false and true: " + Boolean.compare(primitiveBool2, primitiveBool1));  // -1
    }
}

Explanation:

equals() is used to compare two Boolean objects for equality.
Primitive booleans are compared using the == operator.
Boolean.compare() compares two primitive boolean values and returns:
0 if they are equal,
1 if the first value is true and the second is false,
-1 if the first value is false and the second is true.

6. Parsing Strings to Booleans

The Boolean class provides the parseBoolean() method to convert a string to a primitive boolean.

If the string is “true” (ignoring case), the method returns true. For any other string, it returns false.

Example 5: Parsing Strings to Boolean Values

public class ParseBooleanExample {
    public static void main(String[] args) {
        // Parsing valid strings
        boolean bool1 = Boolean.parseBoolean("true");
        boolean bool2 = Boolean.parseBoolean("TrUe");  // Case-insensitive
        boolean bool3 = Boolean.parseBoolean("false");

        // Parsing invalid strings (defaults to false)
        boolean bool4 = Boolean.parseBoolean("yes");
        boolean bool5 = Boolean.parseBoolean("123");

        // Displaying parsed values
        System.out.println("bool1: " + bool1);  // true
        System.out.println("bool2: " + bool2);  // true
        System.out.println("bool3: " + bool3);  // false
        System.out.println("bool4: " + bool4);  // false
        System.out.println("bool5: " + bool5);  // false
    }
}

Explanation:

Boolean.parseBoolean() converts the string “true” (case-insensitive) to the boolean true. Any other string (e.g., “false”, “yes”, “123”) is converted to false.

7. Key Considerations

Boolean Constants: Always use Boolean.TRUE and Boolean.FALSE when working with constants instead of creating new Boolean objects.
Performance: Prefer Boolean.valueOf() over the Boolean constructor for creating Boolean objects because valueOf() uses cached instances for better performance.
Auto-boxing/Unboxing: Java handles conversions between boolean and Boolean automatically, but it’s essential to understand when auto-boxing or unboxing occurs to avoid performance penalties in performance-sensitive areas.
String Parsing: Be cautious when parsing strings to booleans. Only “true” (case-insensitive) returns true, while all other values return false.

Conclusion

In this tutorial, we explored the Boolean class in Java:

Creating Boolean Objects using constructors and the Boolean.valueOf() method.
Methods of the Boolean Class, including booleanValue(), toString(), parseBoolean(), and equals().
Auto-boxing and Unboxing between primitive boolean and the Boolean object.
Comparing Boolean Values using equals() and compare().
Parsing Strings to Booleans using the parseBoolean() method.

By understanding the Boolean class and how to work with boolean values in object form, you can make more efficient use of boolean values in collections, string parsing, and comparisons.

Related posts

Java Data Types Tutorial

Java Number Class Tutorial

Java User Input Tutorial