1.

A Java program begins with a call to which function?

Answer»

When a JAVA program begins, the public static void main(String []args) method is called.

When the Java program needs to be executed, the system looks for the main entry point in the program. This is provided through the main method,

The public static void main(String args[]) is the main method of the Java Program. It is the most important Java Method. It is the entry point of any Java Program. A Java Program cannot be executed without the main method.

Only the args can be changed to a different name but the rest of the method carries the same syntax.

Let us analyze the main method by breaking it up:

  • public : This is the access specifier/access modifier of the main method. It should be public to allow the CLASS to access it. In case of violation of the same, the program will show an error.
  • static : At the start of the runtime, the class is devoid of any object. Thus, the main method needs to be static so that the Java Virtual Machine can set the class to the memory and CALL the main method. If the main method is not static then the JVM won’t be able to call it due to the absence of an object.
  • void : It is the return TYPE of the main method. Each and every method in Java must have a return type.The main method doesn’t return any value that can be accessed by the other methods as the main method can’t be called in any other method. As soon as the main method finishes its execution the program terminates. Hence it wouldn’t be of any use to return a value. If any value is returned then the compiler will show an unexpected return value error.
  • main: It is the name of the main method. This name is already set and can’t be changed. If any changes are made to the main keyword then the compiler tells that the main method couldn’t be found.
  • String args[]:  The main method can accept a single argument which is of the String type. They are also called command line arguments. They can be used and manipulated as normal arguments in the code written in the main method. They are written along with the execution statement.

The following program will illustrate that the main method is run at first:

public class Example {    void display()    {        System.out.println("This is the display method");    }   public static void main(String[] args) // the main method    {        System.out.println("This is the main method");        Example obj = new Example();        obj.display(); // invokes display method    } }

The output is as follows:

$javac Example.java $java Example This is the main method This is the display method


Discussion

No Comment Found