What are the default values of boolean
(primitive) and Boolean
(primitive wrapper) in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
output:
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.
boolean
Can be
true
orfalse
.Default value is
false
.(Source: Java Primitive Variables)
Boolean
Can be a
Boolean
object representingtrue
orfalse
, or can benull
.Default value is
null
.If you need to ask, then you need to explicitly initialize your fields/variables, because if you have to look it up, then chances are someone else needs to do that too.
The value for a primitive
boolean
is false as can be seen here.As mentioned by others the value for a
Boolean
will be null by default.The default value of any
Object
, such asBoolean
, isnull
.The default value for a
boolean
is false.Note: Every primitive has a wrapper class. Every wrapper uses a reference which has a default of
null
. Primitives have different default values:Note (2):
void
has a wrapperVoid
which also has a default ofnull
and is it's only possible value (without using hacks).Boolean is an Object. So if it's an instance variable it will be null. If it's declared within a method you will have to initialize it, or there will be a compiler error.
If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable). If it's declared within a method you will still have to initialize it to either true or false, or there will be a compiler error.
An uninitialized
Boolean
member (actually a reference to an object of typeBoolean
) will have the default value ofnull
.An uninitialized
boolean
(primitive) member will have the default value offalse
.