|
The member variables are of two types- instance variables and the static variables (also known as class variables). As we have seen earlier (Chapter 3 Modifiers), the static variables are associated with class and instance variables are associated with the instance.
Initialization of instance variables
Instance variables are created when an instance of a Java class is created. They are automatically initialized to default values just before the constructor is invoked. The default value is decided based on the type of that instance variable. Table 8.2 summarizes the default values for different data types.
Table 8.2 Default values for initialization of Variables
|
Variable Type |
Default Value |
|
Object reference |
null |
|
byte |
0 |
|
short |
0 |
|
int |
0 |
|
long |
0L or 0l |
|
float |
0.0F or 0.0f |
|
double |
0.0D or 0.0d |
|
boolean |
false |
|
char |
‘\u0000’ |
If the instance variable is of an object reference type, it will be initialized to null otherwise it will be of a primitive type. In that case, it will be initialized to the value shown in the table 8.2. For instance, if it is of type boolean, it will be initialized to false. You can also explicitly initialize a member variable at the time of its declaration. Listing 8.2 illustrates the initialization of instance variables where the variable statusCode is explicitly initialized and the other two variables are automatically initialized.

The variable aSimpleString is a reference to a String object, therefore it is initialized to null. The productID is of primitive type int, hence it is initialized to 0.
Initialization of static variables
Static variables are associated with class rather than the instance. They are automatically initialized to a default value when the class is loaded. Here as well the assigned default value depends on the variable’s type. The table 8.2 of default values for initialization of the instance variables is also applicable for static variables. Listing 8.3 illustrates how the static variable count is automatically initialized.
![]() |
At the time when StaticInitializationTest class is loaded in the JVM, the static variable count is automatically initialized to 0. As the static initializer block is executed after that, it will print the value of count as 0.