Junior — Middle
When exactly does class initialization occur during application startup?
sobes.tech AI
Answer from AI
Class initialization in Java occurs upon the first active use of the class, which can be:
- When creating the first instance of the class (via new).
- When calling a static method of the class.
- When accessing a static field of the class.
- When loading the class through reflection.
At the moment of initialization, the static initialization block is executed, and static fields are initialized.
Example:
public class Example {
static {
System.out.println("Class initialized");
}
public static void method() {
System.out.println("Static method called");
}
}
// Call
Example.method(); // This will trigger class initialization
Thus, class initialization occurs once upon the first active use of the class.