Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why main() is declared public and static in java [duplicate]

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?"
like image 335
AK4 Avatar asked Mar 11 '14 14:03

AK4


People also ask

What is “static” in “public static void main“ in Java?

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 the main method declared static in Java?

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.

What if main () is not public in Java?

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.

Why is the main method of a class public in Java?

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.


1 Answers

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.

like image 101
Lucian Novac Avatar answered Sep 29 '22 18:09

Lucian Novac