I am trying to understand the exact scenario when a class get loaded and initialized. I see the two articles below give different answers
javarevisited-A Class is initialized in Java whenan Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.
Java world-So when are classes loaded? There are exactly two cases: when the new bytecode is executed (for example, FooClass f = new FooClass();) and when the bytecodes make a static reference to a class (for example, System.out).
So when I create an instance of class using new keyword is class loaded or initialized?
Another thing to ask regarding loading due to reference variable:
javarevisited-Class loading is done by Class Loaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs
What does author mean by referencing here? Does he imply if A class have reference variable of B class then B class get loaded when its reference is encountered in A ??
But the author below says class NotUsed is not loaded but I see ClassInitializationTest class having its reference
/** * Java class which is not used in this program, consequently not loaded by JVM */
class NotUsed {
static { System.out.println("NotUsed Class is initialized "); }
}