Java > Core Java > Variables and Data Types > Wrapper Classes
Boolean Wrapper Class and Conditional Logic
This example demonstrates the use of the Boolean
wrapper class and its interaction with conditional logic. It covers creating Boolean
objects, unboxing them to primitive boolean
values, and using them in if
statements. It also showcases the Boolean.parseBoolean()
and Boolean.valueOf()
methods for converting strings to Boolean
values.
Code Snippet: Boolean Wrapper Class Example
This code demonstrates how to create and use Boolean
wrapper objects. Key aspects include:
Boolean
objects using Boolean.valueOf(true)
and Boolean.valueOf(false)
. This is the preferred way to create Boolean
objects.Boolean
objects from strings using Boolean.valueOf("true")
. The method is case-insensitive; any string other than "true" (case-insensitive) will result in false
.Boolean
objects to boolean
primitives using booleanValue()
.Boolean
objects in if
statements, which automatically unboxes the Boolean
object to a boolean
primitive.Boolean.parseBoolean()
: Converting strings to boolean primitives using Boolean.parseBoolean()
. Similar to Boolean.valueOf()
, it's case-insensitive. Any string other than 'true' (case-insensitive) will evaluate to false.
public class BooleanWrapperExample {
public static void main(String[] args) {
// Creating Boolean wrapper objects
Boolean boolObject1 = Boolean.valueOf(true);
Boolean boolObject2 = Boolean.valueOf(false);
// Creating Boolean objects from strings
Boolean boolObject3 = Boolean.valueOf("true"); // Case-insensitive
Boolean boolObject4 = Boolean.valueOf("False");
Boolean boolObject5 = Boolean.valueOf("randomString"); // Returns false
// Unboxing Boolean objects to boolean primitives
boolean boolValue1 = boolObject1.booleanValue();
boolean boolValue2 = boolObject2.booleanValue();
// Using Boolean objects in conditional statements
if (boolObject1) { // Autounboxing happens here
System.out.println("boolObject1 is true");
} else {
System.out.println("boolObject1 is false");
}
if (boolValue2) {
System.out.println("boolValue2 is true");
} else {
System.out.println("boolValue2 is false");
}
// Using Boolean.parseBoolean() - returns primitive boolean
boolean parsedBool1 = Boolean.parseBoolean("TrUe");
boolean parsedBool2 = Boolean.parseBoolean("anyString"); //Returns false if string is not "true" (case insensitive)
System.out.println("boolObject3 from string \"true\": " + boolObject3); //true
System.out.println("boolObject4 from string \"False\": " + boolObject4); //false
System.out.println("boolObject5 from string \"randomString\": " + boolObject5); //false
System.out.println("Parsed boolean from string \"TrUe\": " + parsedBool1); //true
System.out.println("Parsed boolean from string \"anyString\": " + parsedBool2); //false
}
}
Concepts Behind the Snippet
The Boolean
wrapper class represents the primitive boolean
type as an object. It's useful when you need to use boolean values in contexts that require objects (e.g., collections or when you need a nullable boolean value). The valueOf()
method ensures that only two Boolean
objects are created (Boolean.TRUE
and Boolean.FALSE
) unless the system property java.lang.Boolean.BooleanCache.high
is set differently, leading to better memory efficiency.
Real-Life Use Case
Imagine reading configuration settings from a file where boolean values are represented as strings. You can use Boolean.valueOf()
or Boolean.parseBoolean()
to convert these strings to boolean values for use in your application's logic. Another use case is representing the state of a checkbox in a GUI application where the checkbox's state is represented as a Boolean
object.
import java.util.HashMap;
import java.util.Map;
public class BooleanConfigExample {
public static void main(String[] args) {
// Simulate reading configuration from a file
Map<String, String> config = new HashMap<>();
config.put("enableFeature", "true");
config.put("logToFile", "false");
// Retrieve configuration values and convert them to booleans
Boolean enableFeature = Boolean.valueOf(config.get("enableFeature"));
Boolean logToFile = Boolean.valueOf(config.get("logToFile"));
// Use the boolean values in your application
if (enableFeature) {
System.out.println("Feature is enabled.");
} else {
System.out.println("Feature is disabled.");
}
if (logToFile) {
System.out.println("Logging to file is enabled.");
} else {
System.out.println("Logging to file is disabled.");
}
}
}
Best Practices
Boolean.valueOf()
: Use Boolean.valueOf()
for creating Boolean
objects, as it can reuse existing objects (Boolean.TRUE
and Boolean.FALSE
) for better memory efficiency.null
Carefully: Be cautious when dealing with Boolean
objects that might be null
, and handle them appropriately to avoid NullPointerException
.Boolean.valueOf()
returns true
only for the string "true" (case-insensitive) and false
for any other string, including null
.
Interview Tip
Be prepared to discuss the differences between Boolean.valueOf()
and Boolean.parseBoolean()
, their behavior when converting strings to booleans, and the memory implications of using wrapper classes. Also, discuss the immutability of wrapper classes.
When to Use Them
Use Boolean
wrapper classes when:
null
to indicate an unknown or missing value).
Memory Footprint
A boolean
primitive typically takes up 1 byte (although its actual memory usage might be larger due to alignment). A Boolean
object has a larger memory footprint due to object overhead. Be mindful of this when working with large numbers of boolean values.
Alternatives
Using a primitive boolean
array is more efficient for large datasets when you don't need object-oriented features or a potentially absent value.
Pros
Cons
NullPointerException
during unboxing.
FAQ
-
What is the difference between
Boolean.valueOf()
andBoolean.parseBoolean()
?
Boolean.valueOf()
returns aBoolean
object, whileBoolean.parseBoolean()
returns a primitiveboolean
.Boolean.valueOf()
is preferred for creatingBoolean
objects, as it reuses existing instances.Boolean.parseBoolean()
is generally used when you directly need the primitive value. -
What value does
Boolean.valueOf()
return if the input string is not "true" (case-insensitive)?
It returnsBoolean.FALSE
. -
Can I use
null
with a primitiveboolean
?
No, primitiveboolean
types cannot benull
. You can use theBoolean
wrapper class if you need to represent a potentially absent boolean value.