Sunday, 27 November 2016

Why Public Static Void Main in JAVA ?

Hii Friends,
This is Sunny from SmartiesGeeks. Today we found a very important topic where getting problems. They are unable to clear doubts. So here we come with a point "Why Public Static Void Main in Java". Let's deal some aspects of this point that will sure clear your doubts.

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

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

 class Demo{

      public static void main(String[] args){
            //execuion logic place here...

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 main() is 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 main() is 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 main() 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. If I'm wrong at any point please let me know through comment then i will try to modify...

                                     Thank you(Smartyy Sunny)

No comments:

Post a Comment