The method signature of a Java main() method is:
public static void main(String[] args){
...
}
Is there a reason for this method to be static?
The method signature of a Java main() method is:
public static void main(String[] args){
...
}
Is there a reason for this method to be static?
If the main method would not be static, you would need to create an object of your main class from outside the program. How would you want to do that?
Why public static void main(String[] args) ?
This is how Java Language is designed and Java Virtual Machine is designed and written.
Oracle Java Language Specification
Check out Chapter 12 Execution - Section 12.1.4 Invoke Test.main:
Oracle Java Virtual Machine Specification
Check out Chapter 2 Java Programming Language Concepts - Section 2.17 Execution:
Oracle OpenJDK Source
Download and extract the source jar and see how JVM is written, check out
../launcher/java.c
, which contains native C code behind commandjava [-options] class [args...]
:Source: Essentials, Part 1, Lesson 2: Building Applications
The static key word in the main method is used because there isn't any instantiation that take place in the main method. But object is constructed rather than invocation as a result we use the static key word in the main method. In jvm context memory is created when class loads into it.And all static members are present in that memory. if we make the main static now it will be in memory and can be accessible to jvm (class.main(..)) so we can call the main method with out need of even need for heap been created.
If it wasn't, which constructor should be used if there are more than one?
There is more information on the initialization and execution of Java programs available in the Java Language Specification.
there is the simple reason behind it that is because object is not required to call static method , if It were non-static method, java virtual machine creates object first then call main() method that will lead to the problem of extra memory allocation.