[Java] Meaning of Public static void main (String [] args)

public static void main (String [] args) is a required method for running Java. If you make a mistake in even one syntax, an error will occur and you will not be able to execute it. Because each one has its own meaning.

Hello.java


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

The meaning of each item is as follows.

item meaning
public Can be referenced from anywhere
static Instance possible(new)Can be used from the outside without
void No return value
main Method name
String[] Receive the argument as a String type array
args Abbreviationforargumentsinthepluralformofargumentnameandargument(Japanesetranslation:argument)

About args

String [] args are values (command line arguments) specified when the program starts. The argument name args is customarily used as args, but you can use another name. The reason why args is used by convention is that Java is the successor to C and inherits the convention of C.

Argument name used in C language

--argv (argument vector (argument array)) --argc (argument count)

Argument operation check

Hello.java


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

--Replace args with sample

Hello.java


class Hello{
    public static void main(String[] sample) {
        System.out.println(sample[0]);        
    }
}
$ java Hello "Hello world"
Hello world

If the syntax is incorrect

If the syntax is incorrect, the execution result will be as follows.

$ java Hello "Hello world"
error:The main method cannot be found in class Hello. Define the main method as follows:
   public static void main(String[] args)

Wrong syntax example

--When the argument is other than a String type array

Hello.java


class Hello{
    public static void main(Integer[] sample) {
        System.out.println(sample[0]);        
    }
}

Recommended Posts

[Java] Meaning of Public static void main (String [] args)
[Java] What is Public static void main (String [] args)?
Benefits of Java static method
[Java] Speed comparison of string concatenation
Various methods of Java String class
[Java] Correct comparison of String type
[Java] Comparison of String type character strings
Java string
Java static
The story of low-level string comparison in Java
[Java] Get the length of the surrogate pair string
[Java] The confusing part of String and StringBuilder
[Note] Java: Measures the speed of string concatenation
Method name of static factory method learned from Java 8
Check static and public behavior in Java methods