Thursday 8 October 2015

Everything about public static void main( ) in Java

Its more than thousands time you might have written public static void main( ) java. But how many of you really know the details? Whats the reason to write it? What is the meaning of each and every word of it? 
Well.. I believe strongly, whatever you write in your code, you must be fully convinced about why you are writing it. Else it doesnt makes a sense... really IT DOESNT MAKES A SENSE... 

public is the visibility. This can be public, private, protected or (if you omit a value) default.
static is a special [optional] keyword that indicates that this method can be called without creating an instance of this class. Without it, you have to instantiate this class and call this method from the resulting object.
void is the return type of this method, indicating that this method doesn't return anything. Methods must have a return type.
main( ... ) is the name of this method. Methods have to be named. The parentheses indicate that this is a method.
String[] args is a single parameter for the method. String[] is the type of the parameter, indicating an array of Strings. args is the na
me of the parameter. Parameters must be named.
The method signature can therefore be:
public static void main( String[] args )
public static void main( String... args )
note that the varargs version (...) is only valid from Java 5..
If you want to dig more about it here I go : 
If you look into JDK source code (jdk-src\j2se\src\share\bin\java.c):
/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
                   "([Ljava/lang/String;)V");
...
{    /* Make sure the main method is public */
...
mods = (*env)->CallIntMethod(env, obj, mid);
if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */
    message = "Main method not public.";
    messageDest = JNI_TRUE;
    goto leave;
...

No comments:

Post a Comment

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...