The java.lang.Boolean
class encapsulates the primitive boolean
type within an object. This encapsulation allows boolean values to be treated as objects, enabling us to perform various operations on them. Instances of the Boolean
class can hold two values: true
or false
. These instances are immutable, meaning their values cannot be modified after creation.
Key Features of java.lang.Boolean Class
When working with the java.lang.Boolean
class, several key features come into play:
Creating Boolean Instances
To create a Boolean
instance, we can use the constructor methods provided by the class. For example:
Boolean trueValue = new Boolean(true);
Boolean falseValue = new Boolean(false);
Value Comparison
The Boolean
class offers methods to compare two Boolean
objects based on their boolean values:
Boolean firstValue = new Boolean(true);
Boolean secondValue = new Boolean(false);
if (firstValue.equals(secondValue)) {
// Code block for equal values
} else {
// Code block for different values
}
Converting to Primitive boolean
We can convert a Boolean
object to its corresponding primitive boolean
using the .booleanValue()
method:
Boolean boolValue = new Boolean(true);
boolean primitiveBool = boolValue.booleanValue();
Logical Operations
The Boolean
class provides methods for logical AND, OR, and NOT operations:
Boolean firstValue = new Boolean(true);
Boolean secondValue = new Boolean(false);
Boolean resultAND = firstValue && secondValue;
Boolean resultOR = firstValue || secondValue;
Boolean resultNOT = !firstValue;
Methods in java.lang.Boolean Class
The java.lang.Boolean
class offers a variety of methods to manipulate and extract information from Boolean
objects:
compareTo(Boolean otherBoolean)
This method compares the boolean value of the current Boolean
object with another Boolean
object.
hashCode()
Returns the hash code value for the Boolean
object.
toString()
Converts the Boolean
object into a string representation.
valueOf(String s)
Converts a string representation of a boolean value into a Boolean
object.