[Java] [Java] What is Public static void main(String[] args)?

2 minute read

Those who are doing java must see public static void main(String[] args).

It is always a required method to execute.

However, if you make a mistake in any one of these, you will get an error. Why is that?

I was interested, so I will introduce it to the same beginners in the future.

Try to understand the meaning first


class Hello{
    public static void main(String[] args) {
        System.out.println("Hello World");

And the contents are like this.

Surprisingly static is also important for understanding the instance Remember that

Item Meaning
public Can be referenced from anywhere (access modifier)
static Can be used from the outside without needing an instance (new)
void No return value
main method name
String[] Receives an argument as an array of String type
args The abbreviation of arguments in the plural form of argument name and argument.

Who are #args? String[] args are the values (command line arguments) specified when starting the program.

The argument name args is customarily args, but you can use another name. The reason args is customarily used is that Java is the successor to C and inherits the C convention.

What is #static? The main method requires the static modifier. But why don’t you think?

It is usually that you need create an instance of the class if you want to use the methods of the class. (There are too many people who do not remember this for beginners)

SubClass sub = new SubClass();
sub.main(new String[] {"Hello SubClass!"});

But adding the static modifier allows you to access the method without instantiating it with new.

SubClass.main(new String[] {"Hello SubClass!"});

This means that executing the java command does not create an instance of the main class, so the executed main method must have the static modifier.

I need this for the time being

  1. Method name is main
  2. Argument is an array of String type (variable length argument)
  3. The static modifier is added

Attempting to execute a java command for a class that does not meet this condition will fail as follows.

Error: Main method not found in class HelloWorld. Define your main method as follows:
   public static void main(String[] args)

Also, if the return value is set to something other than void, the following error will occur.

Error: Main method must return a value of type void of class HelloWorld.
Define your main method as follows:
   public static void main(String[] args)