Could someone explain what is the difference between Class loading and instantiating a Class. When we load a class with Static variable does it also get instantiated the same ti
Class loading
Whenever the JVM determines it needs a class (to use its static variables, to create a new object, to use its static methods etc) it will load the class and static initialisation blocks will run, static variables are initialised etc. This is (at least under normal circumstances) done only once
SomeClass.someStaticMethod(); //SomeClass is loaded (if its not already)
SomeClass.someStaticVariable; //SomeClass is loaded (if its not already)
SomeClass var=new SomeClass(); //SomeClass is BOTH loaded (if its not already) AND instantiated
As a result the following runs (as an example):
static Vector3d var=new Vector3d(); //static variables are initialised
static{
//static initialisation block are run
}
Instantiating a class
On the other hand you instantiate a class when you create an instance of the class with the new
keyword; instantiating a class is creating an object of the class.
SomeClass var=new SomeClass(); //SomeClass is instantiating (and loaded if its not already)
As a result the constructor runs:
public SomeClass(){
}
and
{
//initialisation block(s) also run (but these are very uncommonly used)
}