Sep 18, 2013

Internal Mechanism of public static void main(String args[])

Internal Mechanism of public static void main(String args[]) in java programming:

Java: public static void main(String args[]): Let us explaining public static void main(String args[]). Java is a platform independent language in which main() method is declared as public as well as static and its return type is void. In main method a String type array parameter is passed. Let us take a look why do we write main() method as public static void main(String args[]). We will explain each term step by step as below-

Why do we use public keyword:

public is an access specifier in java programming i.e. it defines the scope and visibility of class members. main() is also a class member when we declare main() method as public it can be called by JVM. main() is a method which is called by JVM automatically. There are two environment in java programming one is JDK environment and another is JVM environment. If JVM calls a method written in JDK environment then that method need to be declared as public. As we know that when ever we want to call a method out side of the class or package then that method must be declared as public. This is the concept behind main() method declared as public.

Why do we use static keyword:

static is an access access modifier in java programming i.e. it defines characteristics of class members. static member of the class are automatically loaded into memory without creating object of the class and non-static member needs to load into memory with object. So if we don't declare main() method as static then it would be a non-static method and would need to be called by object reference. Unfortunately JVM don't create any object automatically in this situation any instance member will not be instantiated through out its life.

Why do we use void return type:

main() method is automatically called by JVM. Its return type is void i.e. it returns no value. If it have any return type then it would be received by JVM and there is no procedure for using a value received by JVM. So we declare main() method with void return type.

Why do we use String args[]:

In main() method an array instance of String class is passed. Purpose of passing this type parameter is to receive the COMMAND LINE ARGUMENT when program is executed. In String args[], args is an array type variable of class String. Value inputted by command line argument is treated as String type however it is an integer value.

For example-

If user has inputted two integer numbers for addition that will be treated as String in this situation we need to convert these no. into integer type by using parsing technique.

It completes the great explanation of public static void main(String args[]).