Those who are doing java will definitely see ** public static void main (String [] args) **.
It is a necessary method to execute.
However, if you make a mistake in any one of these, an error will occur. Why?
I'm curious, so I'd like to introduce it to the same beginners in the future.
Hello.java
class Hello{
public static void main(String[] args) {
System.out.println("Hello World");
}
}
And the content is like this.
Surprisingly ** static is also important for understanding instances ** so let's remember (commandment)
item | meaning |
---|---|
public | Can be referenced from anywhere(Access modifier) |
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 | Abbreviation for arguments in the plural form of argument name and argument (Japanese translation: argument) |
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.
The main method requires a static qualifier. But why don't you think?
It usually requires ** instantiating a class with new if you want to use the methods of the class **. (This is a problem that too many people do not remember beginners)
SubClass sub = new SubClass();
sub.main(new String[] {"Hello SubClass!"});
However, 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 instantiate the main class, so the main method being executed must have the static modifier.
If you try to execute a java command for a class that does not meet this condition, it will fail as follows.
error:The main method cannot be found in class HelloWorld. Define the 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:The main method should return a value of type void in class HelloWorld.
Define the main method as follows:
public static void main(String[] args)
Recommended Posts