Wednesday, April 18, 2007
Why main method of Java has public static void?
Subscribe to:
Post Comments (Atom)
World of tricky Core Java Q&A(Java SE),Java EE and Open source technologies like Struts,Hibernate,Spring,Velocity etc
Disclaimer
Interview Questions On Java,Java EE Copyright © 2012
6 comments:
Can you please explain in an ellaborated way.. as why it has to be public, satic, void ..
Public makes sense, as it needs to be called from outside the class. Static makes sense too, because it is invoked before any kind of statefulness in the user code.
The "void" part is a little perplexing at first - the java executable itself returns an integer, per K&R C standards - which reflects whether the process succeeds or encountered an error - so why not have main(..) return an int?
IMHO, the reasoning is that there is already built-in exception handling in the language, and that to support BOTH in integer return code like in C and unchecked exceptions from main(..) would be redundant. The exception handling is the more robust of the two maintains contiguity between the flor of main(...) and all the other Java APIs.
main() should be public static void because:
public : It makes that the attributes and operations declared in the main should be accessible every where.
static : static is one per class not one for object even so many instances are created. They are implicitly final.
void: void return type is used to return nothing. So, this indicates main() should not return nothing
public:
because it is called by JVM and ouside of any class.
static:
JVM need not to instantiate a class before it gets called.
void
JVM doesn't want any value to return for further error handling. Once the class gets loaded, it is that class responsibility to handle exceptions/errors
Well done anonymous ..ur are yhe only one who has correctly answered the second question..
anonymous is congratulating anonymous
Post a Comment