As far as we all know Java object's fields is initialized in this way:
false
0
null
My question is which mechanism (method) is doing that job and when is it doing that?
These initializations are done when the new instance of the class is created by JVM . See Creation of new class instances section . It states:
Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden (§8.3).
If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values (§4.12.5).
The default value is as follows for each type of instance variable:
- For type
byte
, the default value is zero, that is, the value of(byte)0
.- For type
short
, the default value is zero, that is, the value of(short)0
.- For type
int
, the default value is zero, that is,0
.- For type
long
, the default value is zero, that is,0L
.- For type
float
, the default value is positive zero, that is,0.0f
.- For type
double
, the default value is positive zero, that is,0.0d
.- For type
char
, the default value is the null character, that is,'\ '
.- For type
boolean
, the default value isfalse
.- For all
reference types
(§4.3), the default value isnull
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.