Thursday, September 5, 2013

PSVM – The main Method




Most of the procedural languages, the execution take place in top to bottom. As for Java is an Object Oriented Programming language and it's work around the objects the execution neither take place from bottom to top or top to bottom. Therefore, it is for Java Virtual Machine[JVM] to know the entry point for the execution of a program and it is decided upon that the execution would start from a main() function.

The main() function restricted to a strict system defined prototype.

public static void main(String args[])

public: The "main" method should declare with access spcifier public, so the method can be accessed from anywhere. It will make this main method invokable without creating an instance of this class.

static: Would allows to call the methos without creating any instance.

void: This keyword indicated that function does not return anything.

main: 'main', is the name of the method and is indicate the entry point of a program execution.

String args[]: This allows users can pass some command line parameter  while executing the program but it is not compulsory.


However, as we know that main() method declared as static and that indicate that the method belongs to the class itself and not to the objects created by the class. So, it is not require to to create an object to call an static method or access a static Data Member. But, while accessing other non-static data member or method from a static member function we need an object.


Example – 1



    public class Static_1
        {
            int a,b;
            static int c;
                public static void main(String args[])
                    {
                        Static_1 S1 = new Static_1();
                        S1.a=40; //Non Static Data Member
                        S1.b=60;
                        c=S1.a+S1.b; //c is static data member
                        System.out.println("Sum = "+c);
                       
                   }
         }


Example – 2



//Static VS Non-Static
    public class Static_2
        {
                public static void main(String args[])
                    {
                        Static_2 S2 = new Static_2();
                        S2.Sum(); //calling a static method
                        product(); //calling a static method
                   }

                public static void product()
                    {
                        int a=10,b=30;
                        System.out.println("Product = "+(a*b));
                    }
                public void Sum()
                    {
                        int a=10,b=30;
                        System.out.println("Sum = "+(a+b));
                    }
        }



No comments: