Our social:

Tuesday, 29 December 2015

Why main() has public static void syntax

The Reason behind

public static void main(String[] arg){}

In the above statement public static void main(String[] arg){} is prototype that is provided by JVM. This static method is given to programmer to write their program execution flow logic like which class we are going to load first, which method execution requires first.  By using main method we are requesting to JVM , hy!!!! jvm you start my program execution in the given fashion.

Now here one question arises that why Main method?
Actually main method is not user defined method, this method is predefined and given by jvm. By following thier prototype we are writing our logic here.
Then another question is why main method has public static void main(){} syntax.

why public?
public is because our program executed by jvm and we all know jvm resides outside of our class and package. In case we define private and protected then, the scope of main() method will be restricted and can not be accessed outside of the package or class will not be unable to execute or load in JVM. that's why we should write main() as public.

why static?
we are using main() as static, why because to execute our program we need some memory in jvm. And as we know that static is special keyword that provide memory of a method at class loading time. So at the time of public class or main method class loading jvm will provide memory to main method. Once main() method gets memory then it will starts execution of our program sequentially.

why void?
main()method not returning any values and there is also no need to return any values. It is only use to execute programs that's why it is declared as void.

NOTE:this is my analyzation and gathered from internet, if i am wrong on any point please correct me through comment then i will try to modify...
                                     Thank you(Smartyy Sunny)


Post a Comment