Site icon TestingDocs.com

The Java main method

Overview

In this tutorial, we will discuss the Java main method. In Java, you need to have a method named main in at least one class if we are developing a standalone Java application.

A  Java program needs to start its execution somewhere. A Java application starts by executing the main method of some Java class. We can choose the name of the class to execute, but not the name of the method. The method must always be called main. The main method is an entry point used by JVM to kick-start the execution of the Java application. It contains a String array as the argument.

public

A method if declared public can be accessed by all other classes outside. In Java, the main method is public, so it is visible to all other classes. JVM classes need to be able to access it.

static

A static method can be accessed without creating the instance or object of the class. So, JVM does not need to create the instance of the class, where the main method resides, to call the main method.

void

The main method doesn’t return any value to the caller i.e. the JVM.

Automatically creating the main method in Eclipse IDE for a class:

Project >> New >> Class

Check the main as shown in the below picture :

 

Running the class which has the main method:

We can run the Java application in many ways from the command line, from within the IDE, etc. However, as stated earlier, we will stick to the Eclipse IDE.

Right-click on the class with the main method

Choose  Run As >> Java Application.

 

Main Class

 

Right click >> Run As >> Run Configuration

Digging further, we can have as many classes as we want in our project with a main() method. But, the JVM needs to be instructed to run one of them at a time. We can still call the other main() methods from inside the main() method the JVM executes and you can also start up multiple VMs which each execute a single main() method.

In case you have multiple classes with the main method, we can specify the main class in the run configuration as shown above.

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version