Wednesday, April 18, 2007

Why main method of Java has public static void?

It is the main entry point of a java file. Every java file has just single copy of main method from where main thread is invoked and that's why main method is static. This method can be overloaded but JVM will distinguish public static void main from rest of the overloaded main methods.


NIRMALA on February 24, 2010 at 7:41 PM said...

Can you please explain in an ellaborated way.. as why it has to be public, satic, void ..

DaveDaveDave on April 8, 2010 at 5:47 AM said...

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.

Ramya Deepthi on November 17, 2010 at 2:22 AM said...

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

Anonymous said...


because it is called by JVM and ouside of any class.


JVM need not to instantiate a class before it gets called.


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

Anonymous said...

Well done anonymous ..ur are yhe only one who has correctly answered the second question..

Imtiaz on October 6, 2011 at 1:21 PM said...

anonymous is congratulating anonymous


Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker