Skip to content

Instantly share code, notes, and snippets.

@pavly-gerges
Last active February 24, 2023 12:06
Show Gist options
  • Save pavly-gerges/2aeca8418abdd70242b0e95b463ad996 to your computer and use it in GitHub Desktop.
Save pavly-gerges/2aeca8418abdd70242b0e95b463ad996 to your computer and use it in GitHub Desktop.
Tests different type of initializers in jvm
/**
* 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();
}
}
@pavly-gerges
Copy link
Author

Here is the output:

Exception in thread "Thread-0" java.lang.ExceptionInInitializerError
at TestInitializers.lambda$main$0(TestInitializers.java:17)
	at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.ArithmeticException: / by zero
	at TestInitializers$TestClassInitializer.<clinit>(TestInitializers.java:10)
	... 2 more
Exception in thread "Thread-1" java.lang.ArithmeticException: / by zero
	at TestInitializers$TestObjectInitializer.<init>(TestInitializers.java:13)
	at TestInitializers.lambda$main$1(TestInitializers.java:21)
	at java.base/java.lang.Thread.run(Thread.java:829)

@pavly-gerges
Copy link
Author

pavly-gerges commented Feb 24, 2023

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