Lesson 6 | Initializers |
Objective | Describe how static and non-static Initializers are declared and used. |
Types of Java Initializers
Java supports the declaration of special code blocks that are part of a class declaration but not part of a method. These code blocks are referred to as
initializers[1]. Two types of initializers are supported:
static
and
- non-
static
.
Static initializers
Static initializer[2] are used to initialize the
static
variables of a class or invoke the methods of
static
variables. They are declared as follows:
static {
// Initialization code
}
Static initialization blocks are also known as,
static initializer
static blocks
Why are static blocks important in Java ?
Generally, we can initialize static data members or class variables directly
but sometimes we require an operation which needs to be performed before assigning or initializing a static data member,
for which we have flexibility of static blocks in Java.
In this context, operation means the execution of Java logic inside static blocks.
Static initializers are executed when their class is loaded in the order that they appear in the class declaration.
They are not executed when an instance of a class is created. The following program illustrates the use of static
initializers. It displays the output abc
.
class StaticInitializer {
// Note that System.out is a static variable.
static {
System.out.print("a");
}
public static void main(String[] args) {
System.out.println("c");
}
static {
System.out.print("b");
}
}
The output of StaticInitializer is
abc
Non-static initializers
Non-static
initializers differ from static
initializers in that they are used to update and invoke the methods of non-static
variables. They also differ when they are executed. Non-static
initializers are not executed when their class is loaded.
They are executed (in the order that they appear) when an instance of their class is created (before the object's constructor). Non-static
initializers are declared in the same way as static
initializers except that the static
keyword is omitted.
The following program illustrates non-static
initializers. It displays the value 103.
class Initializer {
int i = 1;
int j = 2;
{
j += i;
}
public static void main(String[] args) {
new Initializer();
}
Initializer() {
System.out.println(j);
}
{
j += 100;
}
}
Objects Methods Initializers - Quiz
[1]
Initializer: A block of code that is used to initialize a variable.
[2]
Static initializer: A block of code that is used to initialize a static variable.