Core Java

Java Main Method Example – public static void main(String[] args)

In this post, we feature a comprehensive example of the Java Main Method – public static void main(String[] args) through a Java Hello World example.

1. Java Main Method Example – public static void main(String[] args)

In every programming language, when a program starts the execution it has to start from somewhere. For Java, the entry point for a program is the main method. In this post, we will examine this very important method and we will learn how to use it to start simple programs like a Hello World output in a Java program. You can also follow this guide where you can find code examples in order to learn Java quickly.

The technologies that we will use in the code examples of this post are:

  • Java 8
  • Eclipse 4.10.0

2. Signature

At first glance, the signature of the main method is a bit complex, as it consists of several keywords. To have a better understanding of it, let’s examine each keyword one by one:

public static void main(String[] args)

public
This is the access modifier which makes the main method visible to all other classes.

static
The main method is invoked through the class it belongs to and we don’t have to create an instance in order to call it.

void
This means that the main method does not return any value.

main
That is the name of the main method which must be in lower letters.

String[] args
The only argument of the main method is an array of Strings passed through the command line. (see section 2.1 how to pass arguments)

Note: In the above signature we must not change any keyword, apart from the argument, as then the main method will be considered as a regular Java method and not the entry point for the program.

3. Alternative Signature

As we said in the previous section, we can only change the argument of the main method and as such an alternative signature can be:

public static void main(String... myArgs)

In the above signature, we see that that the previous argument String[] args is now changed to String... myArgs. By doing this, we still have a valid main method because:

  • The String[] is replaced by String... , a Java 5 feature called vararg which is actually an array representation.
  • The name of the argument can be set to anything and in this case we changed it from args to myArgs.

4. Class with main() method

We now learned how to declare the main method, so let’s add it to a simple Java class:

MainSimpleExample.java

public class MainSimpleExample {

    public static void main(String[] args) {
        System.out.println("I am the main method!");
    }

}

We added the main method to the above class, which prints a very simple output when invoked.

Note: There must be only one main method per class but we can have as many main methods as we want in different classes in a Java project.

Now, let’s create a hello world program in Java using the public static void main(String args[]):

Hello_world.java

public class Hello_World {
	public static void main(String args[]){  
	     System.out.println("Hello world!!");  
	    }  
}

The output is:

Hello world!!

5. Executing main()

In this section, we will look at two different ways to execute the main method.

5.1 Command Line Execution

Let’s see how to execute and pass arguments to the main method from the command line. First, we need to make sure that Java is installed in our operating system, so we open a terminal (either in Mac, Unix or Windows) and execute:

$ java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)

We confirm that Java 8 is installed in our system. Then we create a class that has a main method which prints all the arguments we pass to it:

MainArgsExample.java

import java.util.Arrays;

public class MainArgsExample {

    public static void main(String[] args) {
        System.out.println("My favourite colours are " + Arrays.toString(args));
    }
}

We save the above class to a file named MainArgsExample.java. The Arrays.toString method helps us print the arguments in a nice format. Now let’s compile this class:

$ javac MainArgsExample.java

The above command generates the byte-code class file MainArgsExample.class in the same location with the java file. Now we are ready to execute the main method and pass arguments to it:

$ java MainArgsExample red blue
My favourite colours are [red, blue]

As we saw in the above example, the arguments passed to the main method are separated by space and printed in the output successfully.

5.2. Execution in Eclipse

As developers, we want to avoid the hassle of having to go through all those commands we saw in the previous section when we want to execute the main method. An IDE, such as Eclipse, makes our life easier as it compiles the java files for us. Our only concern is to run the main method and pass the arguments. Let’s see how to do that in Eclipse.

We open in Eclipse the same MainArgsExample.java file we created in the previous section and we right click on the main method:

Java public static void main - java hello world - Configurations Menu Item
Run Configurations Menu Item in Eclipse

We select Run Configurations and the menu appears:

Java public static void main - Configurations Menu in Eclipse
Run Configurations Menu in Eclipse

Under the Java Application menu item, we see our MainArgsExample class. We click on the Arguments tab where we set our arguments in the Program arguments section. Finally we click Runand the main method gets executed and its output is shown on the Console:

Java public static void main - Console View in Eclipse
Console View in Eclipse

The above output successfully prints the arguments we passed to the main method using Eclipse.

6. Main Thread

Java is a multi-threaded programming language which means a program can contain at least one thread while running. The one thread which is necessary for a Java program to run is called the main thread. This thread is the first thread of the program that starts running when the main method is executed. Let’s take a look below how to return a reference to the main thread:

MainThreadExample.java

public class MainThreadExample {

    public static void main(String[] args) {
        Thread t = Thread.currentThread();
        System.out.printf("The current thread name is '%s' which belongs to group '%s'", t.getName(),
                t.getThreadGroup().getName());
    }

}

In the above example, we retrieve the main thread by calling the Thread.currentThread(). There is no other thread running so the current thread is the main thread. Then we output the name and group of the main thread by running the main method and starting the program:

Output

The current thread name is 'main' which belongs to group 'main'

As we see from the above output, Java sets the name of the main thread to main and the group to main as well.

7. Can we overload or override main()?

Overloading and overriding methods is a very important concept of an Object Oriented language like Java. For more details about those concepts see the Java OOPS Concepts Tutorial. In the following sections, we will see if we can overload and override the main method of Java.

7.1 Overloading main()

Overloading a method is when having the same method name with different arguments and same return type. We can overload the main method but then the new method is considered as a regular Java method. Below we demonstrate this:

MainOverloadExample.java

public class MainOverloadExample {

    public static void main(String[] args) {
        System.out.println("I am the main method - execution starts here");
    }
    
    public static void main(int[] args) {
        System.out.println("I am an overloaded version of the main method but not the entry point of execution");
    }
}

In the code above, we overload the main method by creating another method with the same name and different arguments. Now, the new overloaded main method is not the entry point for the program. As a best practice we should avoid overloading the main method.

7.2. Overriding main()

When a class inherits and implements a method of another class, called the superclass, we say that it overrides the method. Methods that are declared static can’t be overridden because they belong to the class and not to the instances at runtime. As such, the main method, being static, can’t be
overridden.

8. Summary

In this post, we examined the signature of the most important Java method, the Java Main Method – public static void main(String[] args). We also took a look at how Java invokes the main method and creates the main thread when we start a program. Finally, we saw what it means to overload and override the main method.

You can also check this article of a Java Hello World example.

9. Download the Eclipse project

Download
You can download the full source code of the above examples here: Java Main Method Example – public static void main(String[] args)

Last updated on Feb. 10th, 2020

Lefteris Karageorgiou

Lefteris is a Lead Software Engineer at ZuluTrade and has been responsible for re-architecting the backend of the main website from a monolith to event-driven microservices using Java, Spring Boot/Cloud, RabbitMQ, Redis. He has extensive work experience for over 10 years in Software Development, working mainly in the FinTech and Sports Betting industries. Prior to joining ZuluTrade, Lefteris worked as a Senior Java Developer at Inspired Gaming Group in London, building enterprise sports betting applications for William Hills and Paddy Power. He enjoys working with large-scalable, real-time and high-volume systems deployed into AWS and wants to combine his passion for technology and traveling by attending software conferences all over the world.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button