The title might be too long but i'll explain myself.
Usually, when I creates a main mathod, i put it in the class that i start with. Lately i have seen other people codes and saw that they put the main mathod in a new class.
I thought about it and this question came in my mind.
When i start the program, does instance of the class that contains the main mathod is created? So when I create a new instance of the same class in the main mathod, will it create 2 instances or the main is not related to the class itself and the class has no instance in the first place, like statics can't use non-static variable?
No. There is a reason
main()
method ispublic
andstatic
. You don't have to create instance of the class in which it is defined. Thus when you execute your program, the class which containsmain()
will be loaded, initialized and thenmain()
will be executed WITHOUT creating an instance of the enclosing class. That's why you can't accessthis
frommain()
Main method signature : public static void(String args[])
Static: Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method. If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
public: public in Java can be accessible from outside of that class. Since main method is public in Java, JVM can easily access and execute it.
void: its made void which simply means main is not returning anything.
Here's a trick : Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:
The
System.exit(0)
lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:
see this and this
No. Because the
main
method isstatic
. No instance of the enclosing class is automatically created. JLS-12.1 Java Virtual Machine Startup says (in part)