Java Programs  «Prev  Next»
Lesson 4Java main() method
ObjectiveInteraction between the Java Interpreter and the main() Method

Java main() Method

Java is one of the most popular programming languages in the world. It is widely used to build a variety of applications, ranging from simple desktop programs to complex enterprise systems. One of the most important concepts in Java is the main() method, which is the entry point of a Java application. In this article, we will explain what the main() method is, how it works, and why it is so important.
  • What is the main() method?
    The main() method is a special method in Java that serves as the entry point of a Java application. When you run a Java program, the Java Virtual Machine (JVM) looks for the main() method in the class that you specified and executes it. The main() method is defined as follows:
    public static void main(String[] args)
    

    1. public: This keyword indicates that the main() method can be called from anywhere.
    2. static: This keyword indicates that the main() method is a class-level method that can be called without creating an instance of the class.
    3. void: This keyword indicates that the main() method does not return a value.
    4. main: This is the name of the method.
    5. String[] args: This is an array of strings that are passed to the main() method as command-line arguments.


main() method in Java Class

The following code shows a bare-bones Java application which can be 1) compiled and 2) executed from the command-line.

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


line 1 The Skeleton application class definition
line 2The main() method definition
line 3The close of the main() method definition
line 4The close of the application class definition


  • How does the main() method work?
    The main() method is executed by the JVM when you run a Java program. The JVM first looks for the class that contains the main() method and loads it into memory. Then, it calls the main() method and passes any command-line arguments to it. When the main() method is executed, it typically initializes any necessary resources, such as variables, objects, or files. Then, it calls other methods or performs any necessary computations. Finally, it terminates the program by either returning from the main() method or by calling the System.exit() method.
  • Why is the main() method so important?
    The main() method is important because it is the entry point of a Java application. Without a main() method, you cannot run a Java program. The main() method also provides a way to pass command-line arguments to a Java program, which can be useful for configuring the program or providing input data. In addition, the main() method is often used to demonstrate how to use a particular Java feature or library. Many Java tutorials and examples use the main() method to show how a program works or how to use a specific API.



Command-line Java Applications

Command-line Java applications are the simplest of all Java programs. Although they require very little overhead, command-line applications do require a main() method. The execution of an application begins with this method. You already know that the Java interpreter is used to run applications. When an application is executed within the Java interpreter, the interpreter calls the main() method and executes the code within it. The following figure shows how the main() method is called by the Java interpreter to execute an application.
The main method is called by the Java interpreter
The main method is called by the Java interpreter




The main() Method

Running a Java application means picking a particular class and passing its name as an argument to the Java virtual machine. When we did this, the java command looked in our HelloJava class to see if it contained the special method named main() of just the right form. It did, and so it was executed. If it had not been there, we would have received an error message. The main() method is the entry point for applications. Every standalone Java application includes at least one class with a main() method that performs the necessary actions to start the rest of the program.
Our main() method sets up a window (a JFrame) to hold the visual output of the HelloJava class. Right now, it is doing all the work in the application. But in an object-oriented application, we normally delegate responsibilities to many different classes. In the next incarnation of our example, we are going to perform just such a split, creating a second class. We will see that as the example subsequently evolves, the main() method remains more or less the same, simply holding the startup procedure. Let us quickly walk through our main() method, just so we know what it does. First, main() creates a JFrame, the window that will hold our example:
JFrame frame = new JFrame("Hello, Java!");

The word new in this line of code is very important. JFrame is the name of a class that represents a window on the screen, but the class itself is just a template, like a building plan. The new keyword tells Java to allocate memory and actually create a particular JFrame object. In this case, the argument inside the parentheses tells the JFrame what to display in its title bar. We could have left out the "Hello, Java" text and used empty parentheses to create a JFrame with no title, but only because the JFrame specifically allows us to do that.
When frame windows are first created, they are very small. Before we show the JFrame, we set its size to something reasonable
frame.setSize( 300, 300 );

This is an example of invoking a method on a particular object. In this case, the set Size() method is defined by the JFrame class, and it affects the particular JFrame object we have placed in the variable frame. Like the frame, we also create an instance of JLa bel to hold our text inside the window:
JLabel label = new JLabel("Hello, Java!", JLabel.CENTER );

JLabel is much like a physical label. It holds some text at a particular position, in this case, on our frame. This is a very object-oriented concept: using an object to hold some text, instead of simply invoking a method to draw the text and moving on. The reasoning behind this will become clearer later.


Next, we have to place the label into the frame we created:
frame.add( label );

Here, we are calling a method named add() to place our label inside the JFrame. The JFrame is a kind of container that can hold things. We will talk more about that later. main()'s' final task is to show the frame window and its contents, which otherwise would be invisible. An invisible window makes for a pretty boring application.
frame.setVisible( true );

That is the whole main() method. As we progress through the examples in this chapter, it will remain mostly unchanged as the HelloJava class evolves around it.

Java Virtual Machine
The public keyword is an access modifier. When the public keyword is applied to the main() method it means that the method is visible everywhere. The main() method in the Skeleton application is defined as static, which means that the member is associated with the class itself and not a specific instance of the class. When you run this application in the Java interpreter, the main() method is called but there is no code to execute. So, main() returns and the interpreter terminates the application.


The main() method does not appear in Java Applets

The main() method only appears in Java applications, and not in applets. Applets have an init() method that is called to perform applet initialization, but an applet does not execute solely through the init() method in the same way that an application executes through the main() method. As you can see, the main() method is responsible for the start and finish of an application. The following figure shows how an application ends when the main() method finishes executing.
The first requirement in creating an executable Java application is to create a class with a method whose signature (name and method arguments) match the main method, defined as follows:
public class HelloExam {
  public static void main(String args[]) {
    System.out.println("Hello exam");
  }
}

This main method should comply with the following rules:
  1. The method must be marked as a public method.
  2. The method must be marked as a static method.
  3. The name of the method must be main.
  4. The return type of this method must be void.
  5. The method must accept a method argument of a String array or a variable argument of type String.

It is valid to define the method parameter passed to the main method as a variable argument (varargs) of type String:
public static void main(String... args)

To define a variable argument variable, the ellipsis (...) should follow the type of the variable and not the variable itself (a mistake made by lot of new programmers):
The following method declaration will not compile.
public static void main(String args...)

The correct syntax for the Java `main` method to accept multiple arguments is as follows:
public static void main(String... args)
In this version:
  • The `String... args` uses the correct varargs syntax, allowing the `main` method to accept zero or more `String` arguments.
  • Varargs (`...`) must be placed after the type (`String` in this case), indicating that the method can accept any number of `String` arguments.

This is the standard way to declare the `main` method in Java.

SEMrush Software