boolean
About
Definition:
booleanis a primitive data type in Java used to represent one of two values:trueorfalse.Usage: It is primarily used for conditional logic (e.g.,
ifstatements, loops, and logical expressions).Size:
booleanis 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
booleanisfalse.Wrapper Class:
Booleanis the wrapper class forbooleanin thejava.langpackage, which allowsbooleanvalues to be used in collections and provides utility methods.
Characteristics
Two Possible Values Only: The only valid values are
trueandfalse.Not Numeric: Unlike C/C++, Java does not allow
booleanto be treated as an integer (e.g.,true≠1andfalse≠0).Cannot Be Cast to Other Types: No direct or indirect casting to/from
booleanand 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
booleanvariable 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
booleanvariable (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
booleanLogical Operators
Operator
Name
Example
Result
&&
Logical AND
true && false
false
`
`
Logical OR
!
Logical NOT
!true
false
^
Logical XOR
true ^ false
true
Comparison Operators
Operator
Name
Example
Result
==
Equality
a == b
Compares two boolean values
!=
Inequality
a != b
Returns true if values are unequal.
Wrapper Class Boolean
BooleanThe 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 thetruevalue.Boolean.FALSE: A constant holding thefalsevalue.
Static Methods:
Boolean.parseBoolean(String s): Parses a string as a boolean.Boolean.valueOf(String s): Returns aBooleaninstance representing the string value.
Examples
Basic example
Using boolean with streams
boolean with streamsUsing boolean with array
boolean with arrayLast updated