Working of main Method in Java

Price: INR 1,299.00
Was: INR 1,799.00

Let’s understand the working of Main method in Java, Main() method is necessary to start the java application, main() method in Java is a standard method which is used by JVM to start execution of any Java program.

The main() method is referred as an entry point of Java application. main() method in Java is run by the main thread which is a non-daemon thread and Java program runs until main method finishes or any other user thread is running.

When we start JVM by running java command we also provide a name of a class which contains main() method, which is later invoked by JVM to start Java program execution. Syntax of the main method –

public static void main(String args[])

Valid Signature of main() method

A main() method is a standard method and has the pre-specified signature. The main() method is public, static and void and accepts a String[] as an argument only. Following signatures is valid main method signature in Java:

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

if you make any change in the syntax like –

 

 

If you will run the above-written code then it will throw the exception in console like –

Error: Main method not found in class

To overcome from the error you need to correct the main() syntax.

 

Why main() method is public, static & void in Java

main() method in Java is public so that it’s visible to every other class, even which are not part of its package. If it’s not public JVM classes might not able to access it.

The main() method is static in Java so that it can be called without creating any instance. While JVM tries to execute Java program it doesn’t know how to create the instance of the main class as there is no standard constructor is defined for the main class.

The main() method is void in Java because it doesn’t return anything to the caller which is JVM.

 

Selenium Testing Video Tutorial:

0 Comment

Leave a Reply