Monday, December 8, 2008

What is the reason for each keyword of public static void main(String args[])?

Hi, Welcome back to java code online. Most of my friends and readers have asked me this basic question of Java, that what is the reason and use of each of the keywords in "public static void main(String args[])". So here we go.

The reason for each of these keywords as used in Java is explained below.

public: "public" implies the accessibility criteria, since it is used with the "main" method of the code, it has to be public. That is it can be accessed from anywhere. I will talk about the other accessibility modifiers later. For the time being, just bear in mind that if the method is public, then it can be accessed from anywhere.

static: Much can be written about this keyword. For the time being, just bear in mind that, Java environment should be able to call this method without creating an instance of the class, that is the reason for declaring it as "static". Static means that no instance of the class be created for accessing it.

void: "void" is a common keyword and is the same as in C. It implies the return type of the method, since the main does not return anything so the return type must be void.

main: "main" is the first method called by java environment whenever a program is executed. Hence the access specifier has to be public. Moreover it tells the JVM that it is the "main" method of the code, so it needs to start from this method.

String: "String" indicates that the method takes parameters from the command line in form of String. It implies the type of the values returned from the Command Line.

args[]: "args[]" implies that the value or arguments entered from the Command Line are an array.

So overall it implies that public static void main(String args[]) is the main method of the class from which the JVM needs to start, and it is public so that it could be accesed from anywhere in the application. This method is static, and so the class need not be instantiated for using it, and it takes an array of arguments from the Command Line which are of String type.

I hope the information was helpful to you. If you like the solution, then do leave a comment. For more info on Java, keep buzzing Java Code Online.

1 comment:

  1. Thanks a lot for clearing my concepts regarding the various keywords. The concepts seem to be so simple when applied together, and infact it makes great sense to understnad the requirement of public static void main (string[] args) in every java program, that needs to be executed by the JVM directely.

    ReplyDelete

Note: Only a member of this blog may post a comment.