As we know that if we want to create an object
of the class
we need to do something:
class MyClass{
// ...
}
And to create its object
we do:
MyClass MyObj = new MyClass();
Now if we want to create a program in java we need to have a main
method inside the class
and that class
should have the same name as the file name.
For example:
// file MyFile.java
public class MyFile{
public static void main(String[] args){
// ...
}
}
Now the question is that whether the object of MyFile
class will also be created internally by java
when this program runs in order to start the execution of the java file by calling the main
method or does it calls the main
method statically as:
MyFile.main(String[] args);
And what will be the case if I have the class(es) in MyFile
class as:
public class MyFile{
class HelloWorld{
// ...
}
public static void main(String[] args){
// ...
}
}
Or have non-static properties and methods as:
public class MyFile{
int x = 10;
public void MyWorld(){
// ...
}
public static void main(String[] args){
// ...
}
int y = 10;
public void ByeWorld(){
// ...
}
}
Etc etc.
Now, what will be the scenario? Will java
internally creates the object of the MyFile
class? What actions java
will perform in these type of situations in order to both run the program with the help of main
method and as well as also to load the other things before and after of the main
method? What will be the actions performed by the java
internally in these situations?
No instance of the class is created automatically when the JVM starts. The main
method is just invoked statically - that's why it has to be static in the first place.
The class is initialized, so if you have a static initializer, that will be executed before the main
method, but no instance of the class will be constructed. There's no need to do so, and it would introduce unnecessary complications. (What would you expect to happen if you only included constructors with parameters, for example?)
For more details of JVM startup, see chapter 12 of the Java Language Specification.