why should we declare main method? I know that main method is the starting point of the class. But why should only we declare as public static void main(String args[])
?
Basically, because that is how it is defined. (And the reason they decided to use "main" rather than some other name is that "main" is the name used for the entry point of a C or C++ program.)
Why can't we declare as public static void test(String args[])?
Because then the JVM wouldn't be able to find the entry point. Suppose, hypothetically, that the entry point method could be anything. Now consider this example:
public class Test {
public static void foo(String[] args) { ... }
public static void bar(String[] args) { ... }
}
... and this command line ...
$ java Test
Which method gets called? The foo
method? The bar
method?
Is that main key word?
No. It is just a well known method name. As far as the core Java language is concerned, the main
method is just a method with a particular signature. Indeed, you can have other main
methods in the same class with different signatures.
How will JVM knows that it will be the starting point?
Because it is specified that the JVM uses a main
method as the starting point.
Why should main be present in a Java class?
Well ... you don't have to have a main
method in every class ... or indeed any class ... if you have some other way to launch the JVM that uses a different convention for the entry point. But otherwise, you need at least one class with a suitable main
method if you want your application to be runnable.