Lesson 6 | Initializers |
Objective | Describe how static and non-static Initializers are declared and used. |
Types of Java Initializers
Java supports two types of initializers as special code blocks within a class declaration, outside of methods: static initializers and non-static (instance) initializers.
- Static Initializer
- Purpose: Used to initialize static fields or perform one-time setup for the class.
- Syntax: Declared using the
static
keyword within curly braces {}
.
- Execution: Runs only once when the class is loaded into memory by the JVM, before any instances are created or static members are accessed.
- Example:
class Example {
static int staticField;
// Static initializer
static {
staticField = 10;
System.out.println("Static initializer executed");
}
}
- Non-Static (Instance) Initializer
- Purpose: Used to initialize instance fields or perform setup for each instance of the class.
- Syntax: Declared using curly braces
{}
without the static
keyword.
- Execution: Runs every time a new instance of the class is created, before the constructor is called.
- Example:
class Example {
int instanceField;
// Non-static initializer
{
instanceField = 20;
System.out.println("Instance initializer executed");
}
Example() {
System.out.println("Constructor executed");
}
}
Key Differences between Static and Non-Static
Feature |
Static Initializer |
Non-Static Initializer |
Keyword |
static |
None |
Execution Timing |
Once, when class is loaded |
Every time an instance is created |
Purpose |
Initialize static members |
Initialize instance members |
Scope |
Class-level |
Instance-level |
Notes
- Initializers are typically used for complex initialization logic that cannot be handled in a single line.
- Non-static initializers are less common, as constructors often handle instance initialization.
- Multiple initializers (static or non-static) in a class are executed in the order they appear in the source code.
- Static initializers are useful for initializing static resources, like loading configurations or setting up constants.
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 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;
}
}
Output of Java Class with Static Initializers
What will be the result of attempting to compile and run the following code?
public class InitClass{
public static void main(String args[ ] ){
InitClass obj = new InitClass(5);
}
int m;
static int i1 = 5;
static int i2 ;
int j = 100;
int x;
public InitClass(int m){
System.out.println(i1 + " " + i2 + " " + x + " " + j + " " + m);
}
{ j = 30; i2 = 40; } // Instance Initializer
static { i1++; } // Static Initializer
}
Select 1 Option
- The code will fail to compile, since the instance initializer tries to assign a value to a static member.
- The code will fail to compile, since the member variable x will be uninitialized when it is used.
- The code will compile without error and will print 6, 40, 0, 30, 5 when run.
- The code will compile without error and will print 5, 0, 0, 100, 5 when run.
- The code will compile without error and will print 5, 40, 0, 30, 0 when run.
Answer: c
Explanation:
The value 5 is passed to the constructor to the local (automatic) variable m. So the instance variable m is shadowed.
Before the body of the constructor is executed, the instance initializer is executed and assigns values 30 and 40 to variables j and i2,
respectively. A class is loaded when it is first used. For example,
class A1{
static int i = 10;
static { System.out.println("A1 Loaded "); }
}
public class A{
static { System.out.println("A Loaded "); }
public static void main(String[] args){
System.out.println(" A should have been loaded");
A1 a1 = null;
System.out.println(" A1 should not have been loaded");
System.out.println(a1.i);
}
}
When you run it you get the output:
A Loaded
A should have been loaded
A1 should not have been loaded
A1 Loaded
10
Now, A should be loaded first as you are using its main method. Even though you are doing A1 a1 = null; A1 will not be loaded as it is not yet used (so the JVM figures out that it does not need to load it yet.) When you do a1.i, you are using A1, so before you use it, it must be loaded. That's when A1 is loaded. Finally 10 is printed.
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.
