How to Check If a Boolean Variable Is True in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a boolean variable is true in Java. We will explore the fundamental method using the equality operator, delve into handling the Boolean wrapper class, and discuss how to manage potential null values.

Through hands-on examples, you will gain practical experience in writing conditional logic based on boolean values, ensuring your Java code is robust and handles different scenarios effectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/booleans("Booleans") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("Wrapper Classes") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/booleans -.-> lab-559934{{"How to Check If a Boolean Variable Is True in Java"}} java/if_else -.-> lab-559934{{"How to Check If a Boolean Variable Is True in Java"}} java/exceptions -.-> lab-559934{{"How to Check If a Boolean Variable Is True in Java"}} java/wrapper_classes -.-> lab-559934{{"How to Check If a Boolean Variable Is True in Java"}} java/object_methods -.-> lab-559934{{"How to Check If a Boolean Variable Is True in Java"}} end

Use Equality Operator for True Check

In this step, we will explore how to check if a boolean variable is true in Java using the equality operator. While it might seem straightforward, understanding the nuances is important for writing clean and correct code.

In Java, the boolean data type can hold one of two values: true or false. When you have a boolean variable, you often need to check its value to make decisions in your program.

The most common way to check if a boolean variable is true is by using the equality operator ==.

Let's create a simple Java program to demonstrate this.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            boolean isJavaFun = true;
    
            if (isJavaFun == true) {
                System.out.println("Java is fun!");
            } else {
                System.out.println("Java is not fun.");
            }
        }
    }

    Let's look at the new parts of this code:

    • boolean isJavaFun = true;: This line declares a boolean variable named isJavaFun and initializes it with the value true.
    • if (isJavaFun == true): This is an if statement. It checks if the condition inside the parentheses is true. The condition isJavaFun == true uses the equality operator == to compare the value of the isJavaFun variable with the boolean literal true.
    • System.out.println("Java is fun!");: This line will be executed if the condition isJavaFun == true is true.
    • else: This keyword introduces the block of code to be executed if the if condition is false.
    • System.out.println("Java is not fun.");: This line will be executed if the condition isJavaFun == true is false.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program using the javac command in the Terminal:

    javac HelloJava.java

    If there are no errors, a HelloJava.class file will be created in the ~/project directory.

  5. Run the compiled program using the java command:

    java HelloJava

    You should see the output:

    Java is fun!

    This confirms that the if condition isJavaFun == true evaluated to true, and the corresponding message was printed.

While using == true is perfectly valid and easy to understand, in Java, you can simplify the check for true. Since the if statement already evaluates the expression inside the parentheses as a boolean, you can directly use the boolean variable itself as the condition.

Let's modify the code to use this simplified approach:

  1. Open HelloJava.java again in the editor.

  2. Change the if statement to:

    if (isJavaFun) {
        System.out.println("Java is fun!");
    } else {
        System.out.println("Java is not fun.");
    }

    Notice that we removed == true. The if (isJavaFun) statement is equivalent to if (isJavaFun == true).

  3. Save the file.

  4. Compile the modified program:

    javac HelloJava.java
  5. Run the program again:

    java HelloJava

    You will get the same output:

    Java is fun!

    This demonstrates that using the boolean variable directly in the if condition is a more concise and idiomatic way to check if it's true.

In summary, you can use the equality operator == true to check if a boolean is true, but the more common and cleaner way is to simply use the boolean variable itself as the condition in an if statement.

Test with Boolean Wrapper Class

In the previous step, we worked with the primitive boolean type. Java also has a corresponding wrapper class called Boolean. Wrapper classes provide a way to use primitive data types as objects. This is particularly useful when working with collections or when you need to represent a boolean value that might be null.

The Boolean class has two predefined objects for the boolean values: Boolean.TRUE and Boolean.FALSE. These are constant objects representing the boolean values true and false, respectively.

When working with Boolean objects, you can still use the equality operator == to compare them. However, it's important to understand how == works with objects. For objects, == checks if the two variables refer to the exact same object in memory, not just if they have the same value.

Let's modify our program to use the Boolean wrapper class and see how the equality operator behaves.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            Boolean isJavaFunObject = Boolean.TRUE;
    
            if (isJavaFunObject == Boolean.TRUE) {
                System.out.println("Java is fun (using Boolean.TRUE)!");
            } else {
                System.out.println("Java is not fun (using Boolean.TRUE).");
            }
    
            Boolean anotherBooleanObject = true; // Autoboxing
    
            if (anotherBooleanObject == Boolean.TRUE) {
                 System.out.println("Another boolean object is true!");
            } else {
                 System.out.println("Another boolean object is not true.");
            }
        }
    }

    Let's look at the changes:

    • Boolean isJavaFunObject = Boolean.TRUE;: We declare a variable of type Boolean and assign it the constant Boolean.TRUE.
    • if (isJavaFunObject == Boolean.TRUE): We use the equality operator == to compare our Boolean object with the Boolean.TRUE constant. Since isJavaFunObject is assigned Boolean.TRUE, they refer to the same object, so this condition will be true.
    • Boolean anotherBooleanObject = true;: This line demonstrates "autoboxing". Java automatically converts the primitive boolean value true into a Boolean object.
    • if (anotherBooleanObject == Boolean.TRUE): We again use == to compare anotherBooleanObject with Boolean.TRUE. Due to how autoboxing works and Java's caching of Boolean values, for the values true and false, the autoboxed Boolean objects often refer to the same cached instances as Boolean.TRUE and Boolean.FALSE. Therefore, this condition will also likely be true.
  3. Save the file.

  4. Compile the program:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    You should see the output:

    Java is fun (using Boolean.TRUE)!
    Another boolean object is true!

    This confirms that using == with Boolean.TRUE works as expected in these cases because the variables are likely referencing the same underlying Boolean.TRUE object.

However, relying on == for comparing Boolean objects can be risky in more complex scenarios, especially if the Boolean objects are created in different ways or come from different sources. A safer and recommended way to compare Boolean objects for equality of value is to use the .equals() method.

Let's modify the code to use .equals().

  1. Open HelloJava.java in the editor.

  2. Change the if statements to use .equals():

    public class HelloJava {
        public static void main(String[] args) {
            Boolean isJavaFunObject = Boolean.TRUE;
    
            if (isJavaFunObject.equals(Boolean.TRUE)) {
                System.out.println("Java is fun (using equals)!");
            } else {
                System.out.println("Java is not fun (using equals).");
            }
    
            Boolean anotherBooleanObject = true; // Autoboxing
    
            if (anotherBooleanObject.equals(Boolean.TRUE)) {
                 System.out.println("Another boolean object is true (using equals)!");
            } else {
                 System.out.println("Another boolean object is not true (using equals).");
            }
        }
    }

    We replaced == Boolean.TRUE with .equals(Boolean.TRUE). The .equals() method compares the value of the objects, not their memory location.

  3. Save the file.

  4. Compile the program:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    You should see the output:

    Java is fun (using equals)!
    Another boolean object is true (using equals)!

    Using .equals() is the standard and safest way to compare Boolean objects for value equality.

In summary, while == might work for comparing Boolean objects with Boolean.TRUE due to caching, the .equals() method is the preferred and more reliable way to check if a Boolean object represents the value true.

Handle Null Booleans

In the previous step, we learned about the Boolean wrapper class. One key difference between the primitive boolean and the Boolean wrapper class is that a Boolean variable can hold the value null, whereas a primitive boolean cannot. Handling null values is crucial in Java to prevent NullPointerException errors.

A NullPointerException occurs when you try to use a variable that is currently pointing to null as if it were a valid object. For example, calling a method on a null object will result in a NullPointerException.

When checking if a Boolean object is true, you need to be careful if the object might be null.

Let's see what happens if we try to check a null Boolean using the methods we've learned so far.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            Boolean nullableBoolean = null;
    
            // Attempting to use == with null
            if (nullableBoolean == true) {
                System.out.println("This won't be printed.");
            } else {
                System.out.println("Using == with null Boolean.");
            }
    
            // Attempting to use .equals() with null
            // This will cause a NullPointerException!
            // if (nullableBoolean.equals(Boolean.TRUE)) {
            //     System.out.println("This will not be reached.");
            // } else {
            //     System.out.println("This will not be reached either.");
            // }
        }
    }

    In this code:

    • Boolean nullableBoolean = null;: We declare a Boolean variable and explicitly set it to null.
    • if (nullableBoolean == true): We use the equality operator == to compare the null Boolean with the primitive true. When comparing a Boolean object (even if it's null) with a primitive boolean, Java performs "unboxing". It tries to convert the Boolean object to a primitive boolean. If the Boolean object is null, this unboxing process results in a NullPointerException.
    • The commented-out .equals() check would also cause a NullPointerException because you are trying to call the .equals() method on a null object (nullableBoolean).
  3. Save the file.

  4. Compile the program:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    You will see an error message in the terminal, indicating a NullPointerException:

    Exception in thread "main" java.lang.NullPointerException
        at HelloJava.main(HelloJava.java:6)

    This shows that directly comparing a potentially null Boolean with a primitive boolean using == or calling .equals() on it can lead to a NullPointerException.

To safely handle potentially null Boolean objects, you should always check if the object is null before attempting to unbox it or call methods on it.

Here's how you can safely check if a Boolean object is true:

  1. Open HelloJava.java in the editor.

  2. Replace the code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            Boolean nullableBoolean = null;
            Boolean trueBoolean = Boolean.TRUE;
            Boolean falseBoolean = Boolean.FALSE;
    
            // Safely check if nullableBoolean is true
            if (nullableBoolean != null && nullableBoolean == true) {
                System.out.println("nullableBoolean is true (safe check).");
            } else {
                System.out.println("nullableBoolean is not true or is null (safe check).");
            }
    
            // Safely check if trueBoolean is true
            if (trueBoolean != null && trueBoolean == true) {
                System.out.println("trueBoolean is true (safe check).");
            } else {
                System.out.println("trueBoolean is not true or is null (safe check).");
            }
    
            // Safely check if falseBoolean is true
            if (falseBoolean != null && falseBoolean == true) {
                System.out.println("falseBoolean is true (safe check).");
            } else {
                System.out.println("falseBoolean is not true or is null (safe check).");
            }
    
            // Alternative safe check using equals
            if (Boolean.TRUE.equals(nullableBoolean)) {
                 System.out.println("nullableBoolean is true (safe equals check).");
            } else {
                 System.out.println("nullableBoolean is not true or is null (safe equals check).");
            }
    
             if (Boolean.TRUE.equals(trueBoolean)) {
                 System.out.println("trueBoolean is true (safe equals check).");
             } else {
                 System.out.println("trueBoolean is not true or is null (safe equals check).");
             }
        }
    }

    In this updated code:

    • if (nullableBoolean != null && nullableBoolean == true): We first check if nullableBoolean is not null using nullableBoolean != null. The && operator means that the second part of the condition (nullableBoolean == true) will only be evaluated if the first part (nullableBoolean != null) is true. This prevents the NullPointerException. If nullableBoolean is null, the first part is false, and the whole condition is false without evaluating the second part.
    • if (Boolean.TRUE.equals(nullableBoolean)): This is another safe way to check if a Boolean object is true, even if it's null. By calling .equals() on the known non-null object Boolean.TRUE and passing the potentially null object nullableBoolean as an argument, we avoid the NullPointerException. The .equals() method is designed to handle null arguments gracefully; Boolean.TRUE.equals(null) will simply return false.
  3. Save the file.

  4. Compile the program:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    You should see the output:

    nullableBoolean is not true or is null (safe check).
    trueBoolean is true (safe check).
    falseBoolean is not true or is null (safe check).
    nullableBoolean is not true or is null (safe equals check).
    trueBoolean is true (safe equals check).

    This demonstrates how to safely check the value of a Boolean object, even when it might be null, using both the != null check combined with == true and the Boolean.TRUE.equals() method.

Always remember to consider the possibility of null when working with Boolean objects to avoid runtime errors.

Summary

In this lab, we learned how to check if a boolean variable is true in Java. We started by using the equality operator == to compare a boolean variable directly with the boolean literal true. This is the most common and straightforward method for checking the value of a primitive boolean.

We also explored how to handle Boolean wrapper objects, which can be null. We learned that directly comparing a Boolean object with true using == might not work as expected due to object identity. Instead, we should use the equals() method or unbox the Boolean object to its primitive boolean value before comparison. Finally, we addressed the importance of handling potential NullPointerException when working with nullable Boolean objects by checking for null before attempting to access their value.