Last active
February 24, 2023 12:06
-
-
Save pavly-gerges/2aeca8418abdd70242b0e95b463ad996 to your computer and use it in GitHub Desktop.
Tests different type of initializers in jvm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Tests different type of initializers in jvm: | |
* 1) <clinit>: stands for class or the static initializer, called only once on the first reference of the class name. | |
* 2) <init>: is the class object initializer or the instance initializer called whenever creating a new object and it resembles the class constructor. | |
* | |
* @author pavl_g | |
*/ | |
public class TestInitializers { | |
static class TestClassInitializer { | |
public static int len = 00; | |
} | |
static class TestObjectInitializer { | |
public int len = 0/0; | |
} | |
public static void main(String[] args) { | |
new Thread(() -> { | |
TestClassInitializer.len = 2; | |
}).start(); | |
new Thread(() -> { | |
TestObjectInitializer ob = new TestObjectInitializer(); | |
}).start(); | |
} | |
} |
Notice the stack top is the frame that leads to the exception:
at TestInitializers$TestClassInitializer.<clinit>(TestInitializers.java:10)
Where; <clinit>
: stands for the class initializer and executed only and only once when the class first referenced by its name and it resembles the static {}
initializer, the class variables or the static fields are all initialized with the class initializer at the class first use.
And here:
at TestInitializers$TestObjectInitializer.<init>(TestInitializers.java:13)
Where; <init>
is the class object or the instance initializer and it's the constructor of the class and it's executed for each newly created object, the instance variables or the class members are initialized with the object.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the output: