+ 1

Why do we need to define the main function as public and static??

18th Jul 2017, 11:04 AM
Himanshu Sharma
Himanshu Sharma - avatar
4 Réponses
0
main is the insertion point of compiler to run the program. The main method must be public so it can be found by the JVM when the class is loaded. Similarly, it must be static so that it can be called after loading the class, without having to create an instance of it....
18th Jul 2017, 11:16 AM
Naveed Jeelani Khan
Naveed Jeelani Khan - avatar
+ 1
public because everyone should be able to call it. The JVM is definitely not part of your program and public is the only way to let it access main method of your program. static because when loading the program, there is going to be no instance of the class that main is defined in. Since only static methods allow to be called without object of the enclosing class, this is required. You did not ask, but to be complete, void because the JVM likely has other means of reading exit status and does not require any non void return.
18th Jul 2017, 11:19 AM
Venkatesh Pitta
Venkatesh Pitta - avatar
0
We create main() but we don't call it ,it is called by jvm .so we make it public and static because it does not require the reference of an object to be called.
18th Jul 2017, 11:21 AM
siddhant srivastava
siddhant srivastava - avatar
0
Public Becuase all classes should access it and static becuase u won't need to repeat data in it (to lessen the storage that u use)
18th Jul 2017, 9:30 PM
Ishaq Za'rour