Tuesday, February 27, 2018

Public Static Void main explained

This is my notes on public static void main method which we use regularly in our Java Code. I just literally used it without knowing why it is structured like that, so I started looking for this. Below are my points, Please do correct me if I am wrong.
Before going into deep what exactly is happening let us see the structure of this method.
PUBLIC  STATIC  VOID  MAIN (STRING A[])
Here
Public keyword is one of the Access Modifiers which  are available in Java
Static keyword is used for class-method binding
Void specifies the return type
Main is the method name
String A[] : String represents datatype and A represents the variable name

Basically when we execute the “.java” code it creates a “.class” file with the same name which we have given for “.java” code. When we try to execute this class file the JVM instance will takes the class name and by defaults searches for main method.

Here it will not create any object to that class instead it searches for the main method which is bound to that class, so for this purpose we need to specify the “Static” keyword  because “Static” keyword helps to bind the method to that particular class instead to the object of that class.
Just binding is not sufficient but also we need to take care of its accessibility, so for this purpose we use the “public” keyword which specifies that this method can be accessible by other classes also.
So now we can access the main method directly using the class itself.
For example, consider the below sample java code.

public class Sample {
public static void main(String a[])
{
System.out.println("Welcome to codeanyway blog");
}
}
As we specified the static keyword now the JVM can access the main() as Sample.main() directly.
     Now there is another constraint in Java that is every method should have a return type. We specified it void as we are not returning any data in this method.
    We are giving parameters to main method because it facilitates us to pass data during execution.