Boolean vs boolean in Java
What is the difference between Boolean and boolean in Java? Learn how boolean is a primitive data type for storing true/false values, while Boolean is the wrapper class that provides methods to work with boolean values as objects.
In Java, both boolean and Boolean are used to represent true/false values, but they serve different purposes. Understanding the distinction between the two can help you decide which one to use depending on your needs.
boolean (Primitive Data Type):
- Definition: boolean is a primitive data type that can only hold one of two values: true or false.
- Memory: It consumes less memory (1 bit) since it stores only the two possible values.
- Default Value: The default value for a boolean is false.
- Usage: Used for simple conditional statements or flags where an object wrapper is unnecessary.
Example:
boolean isActive = true;
Boolean (Wrapper Class):
- Definition: Boolean is an object wrapper class for the primitive boolean type. It provides utility methods like parseBoolean() and toString() to work with boolean values as objects.
- Memory: Since it’s an object, it consumes more memory compared to the primitive boolean.
- Default Value: The default value for a Boolean is null (not false), as it's an object reference.
- Usage: Often used in collections (e.g., ArrayList) and when you need to treat a boolean as an object or deal with nullable values.
Example:
Boolean isActive = Boolean.TRUE;
Key Differences:
- boolean is primitive, takes less memory, and can't be null.
- Boolean is an object that can be null and provides methods for manipulation.
Which to Use?
- Use boolean when you just need a simple true/false flag and don't need object features.
- Use Boolean when you need to store a null value or require object-related operations, like storing in a collection or converting between true/false strings.