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.
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.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.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 namedisJavaFunand initializes it with the valuetrue.if (isJavaFun == true): This is anifstatement. It checks if the condition inside the parentheses istrue. The conditionisJavaFun == trueuses the equality operator==to compare the value of theisJavaFunvariable with the boolean literaltrue.System.out.println("Java is fun!");: This line will be executed if the conditionisJavaFun == trueistrue.else: This keyword introduces the block of code to be executed if theifcondition isfalse.System.out.println("Java is not fun.");: This line will be executed if the conditionisJavaFun == trueisfalse.
Save the file (Ctrl+S or Cmd+S).
Compile the program using the
javaccommand in the Terminal:javac HelloJava.javaIf there are no errors, a
HelloJava.classfile will be created in the~/projectdirectory.Run the compiled program using the
javacommand:java HelloJavaYou should see the output:
Java is fun!This confirms that the
ifconditionisJavaFun == trueevaluated totrue, 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:
Open
HelloJava.javaagain in the editor.Change the
ifstatement to:if (isJavaFun) { System.out.println("Java is fun!"); } else { System.out.println("Java is not fun."); }Notice that we removed
== true. Theif (isJavaFun)statement is equivalent toif (isJavaFun == true).Save the file.
Compile the modified program:
javac HelloJava.javaRun the program again:
java HelloJavaYou will get the same output:
Java is fun!This demonstrates that using the boolean variable directly in the
ifcondition is a more concise and idiomatic way to check if it'strue.
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.
Open the
HelloJava.javafile in the WebIDE editor.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 typeBooleanand assign it the constantBoolean.TRUE.if (isJavaFunObject == Boolean.TRUE): We use the equality operator==to compare ourBooleanobject with theBoolean.TRUEconstant. SinceisJavaFunObjectis assignedBoolean.TRUE, they refer to the same object, so this condition will betrue.Boolean anotherBooleanObject = true;: This line demonstrates "autoboxing". Java automatically converts the primitivebooleanvaluetrueinto aBooleanobject.if (anotherBooleanObject == Boolean.TRUE): We again use==to compareanotherBooleanObjectwithBoolean.TRUE. Due to how autoboxing works and Java's caching ofBooleanvalues, for the valuestrueandfalse, the autoboxedBooleanobjects often refer to the same cached instances asBoolean.TRUEandBoolean.FALSE. Therefore, this condition will also likely betrue.
Save the file.
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaYou should see the output:
Java is fun (using Boolean.TRUE)! Another boolean object is true!This confirms that using
==withBoolean.TRUEworks as expected in these cases because the variables are likely referencing the same underlyingBoolean.TRUEobject.
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().
Open
HelloJava.javain the editor.Change the
ifstatements 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.TRUEwith.equals(Boolean.TRUE). The.equals()method compares the value of the objects, not their memory location.Save the file.
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaYou 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 compareBooleanobjects 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.
Open the
HelloJava.javafile in the WebIDE editor.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 aBooleanvariable and explicitly set it tonull.if (nullableBoolean == true): We use the equality operator==to compare thenullBooleanwith the primitivetrue. When comparing aBooleanobject (even if it'snull) with a primitiveboolean, Java performs "unboxing". It tries to convert theBooleanobject to a primitiveboolean. If theBooleanobject isnull, this unboxing process results in aNullPointerException.- The commented-out
.equals()check would also cause aNullPointerExceptionbecause you are trying to call the.equals()method on anullobject (nullableBoolean).
Save the file.
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaYou 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
nullBooleanwith a primitivebooleanusing==or calling.equals()on it can lead to aNullPointerException.
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:
Open
HelloJava.javain the editor.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 ifnullableBooleanis notnullusingnullableBoolean != null. The&&operator means that the second part of the condition (nullableBoolean == true) will only be evaluated if the first part (nullableBoolean != null) istrue. This prevents theNullPointerException. IfnullableBooleanisnull, the first part isfalse, and the whole condition isfalsewithout evaluating the second part.if (Boolean.TRUE.equals(nullableBoolean)): This is another safe way to check if aBooleanobject istrue, even if it'snull. By calling.equals()on the known non-null objectBoolean.TRUEand passing the potentiallynullobjectnullableBooleanas an argument, we avoid theNullPointerException. The.equals()method is designed to handlenullarguments gracefully;Boolean.TRUE.equals(null)will simply returnfalse.
Save the file.
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaYou 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
Booleanobject, even when it might benull, using both the!= nullcheck combined with== trueand theBoolean.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.



