Why is the main declared as public and static?
public static void main(String arg[])
{}
acording to ans in java
"The method is static because otherwise there would be ambiguity: which constructor should be called?"
Understanding “static” in “public static void main” in Java. Following points explain what is “static” in the main () method: main () method: The main () method, in Java, is the entry point for the JVM (Java Virtual Machine) into the java program. JVM launches the java program by invoking the main () method. Static is a keyword.
Why is main method declared static in Java? The main method is static in Java, so the JVM can directly invoke it without instantiating the class’s object.
We know that anyone can access/invoke a method having public access specifier. The main method is public in Java because it has to be invoked by the JVM. So, if main()is not public in Java, the JVM won’t call it.
1. The main method in Java is public so that it's visible to every other class, even which are not part of its package. if it's not public JVM classes might not able to access it. 2. The main method is static in Java so that it can be called without creating any instance.
public - The main method is called by the JVM to run the method which is outside the scope of the project therefore the access specifier has to be public to permit a call from anywhere outside the application.
static - When the JVM makes a call to the main method there is no object that exists for the class being called therefore it has to have static method to allow invocation from class.
void - Java is a platform independent language, therefore if it returns some value, then the value may have a different meaning between different platforms so unlike C it can not assume a behavior of returning value to the operating system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With