About
Definition:
boolean
is a primitive data type in Java used to represent one of two values:true
orfalse
.Usage: It is primarily used for conditional logic (e.g.,
if
statements, loops, and logical expressions).Size:
boolean
is not explicitly defined to occupy a specific number of bits in memory by the Java specification, though many implementations use 1 byte.Default Value: The default value of
boolean
isfalse
.Wrapper Class:
Boolean
is the wrapper class forboolean
in thejava.lang
package, which allowsboolean
values to be used in collections and provides utility methods.
Characteristics
Two Possible Values Only: The only valid values are
true
andfalse
.Not Numeric: Unlike C/C++, Java does not allow
boolean
to be treated as an integer (e.g.,true
â‰1
andfalse
â‰0
).Cannot Be Cast to Other Types: No direct or indirect casting to/from
boolean
and numeric or other types is allowed.Control Flow: It is foundational for control flow constructs (
if
,while
,do-while
,for
, etc.).Immutable: The value of a
boolean
variable cannot be altered directly; a new assignment is needed.Logical Operations Support: Works with logical operators like
&&
,||
, and!
for combining and negating conditions.Memory Usage: Though not standardized, the JVM typically allocates 1 byte for a
boolean
variable (smallest addressable unit of memory).Boolean Arrays: Boolean arrays may use 1 bit per value internally (optimized by JVM), though this varies by implementation.
Operations with boolean
boolean
Logical Operators
Comparison Operators
Wrapper Class Boolean
Boolean
The Boolean
class in java.lang
provides utilities for working with boolean
values.
Key Features:
Object Representation of
boolean
: Allows usage in Collections (e.g.,List<Boolean>
).Constants:
Boolean.TRUE
: A constant holding thetrue
value.Boolean.FALSE
: A constant holding thefalse
value.
Static Methods:
Boolean.parseBoolean(String s)
: Parses a string as a boolean.Boolean.valueOf(String s)
: Returns aBoolean
instance representing the string value.
Examples
Basic example
Using boolean
with streams
boolean
with streamsUsing boolean
with array
boolean
with arrayLast updated
Was this helpful?