DEV Community

CodeStorm
CodeStorm

Posted on • Edited on

Understanding the Java Main method.

Writing your first Java "Hello World" application is pretty exciting. When you start your Java journey, you are told this is the syntax to write the program, and you just go along with it. Today, we will break down the reasons behind the main method of your Java code.

Let's consider the following "Hello World" code:

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

    System.out.println("Hello - " +args[0]+" "+args[1]);
    }
}
Enter fullscreen mode Exit fullscreen mode

It has three main components: a class "Helloworld", a public method "main", and an array of strings "args".

1.The keyword class defines your Java class. As an object-oriented language, everything must be inside a class. It can have any name as long as your file name is the same. This tells the JRE which class to look for.

2.Then comes your main method. It has to be named "main" for the JRE to recognize it, as it calls the main method to execute your program.

Breaking down the method signature:

public – Access specifier. It has to be public for the JRE to call the function. Other access modifiers include private and protected, which cannot be called from outside the class.

static – The static keyword defines the method as a static method, meaning the JRE can call this method without creating an object of your class.
i.e instead of this -

HelloWorld obj = new HelloWorld();
obj.main(args);
Enter fullscreen mode Exit fullscreen mode

it can directly call this -

HelloWorld.main(args);
Enter fullscreen mode Exit fullscreen mode

void – The return type of your program. This has to be void so that when your program finishes, it actually terminates and returns nothing.

3.The parameter String[] args – This is called command-line arguments. Just like you pass information to methods inside the program, you can pass values to your main program as an array of arguments (you can call it "args" or literally any variable name).

Example on how to use it (use space to give multiple arguments):

java myprogram arg1 arg2

java HelloWorld There,General Kenobi

will give output -

Output with command line arguments

If you are using eclipse you can pass this arguments in configuration option -

passing commandline arguments in Eclipse

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more