Why the main method is declared as static in java?
In a simple Java program, we declare the main method as follows:
public class Employee {
// main method
public static void main(String[] args) {
}
}
The method is named main
.
When using the java filename command
, the JVM loads the Java class into memory and searches for the main
class in the Java file. main method is an entry file for execution.
If the main
method is not found, it throws the NoClassFoundError exception
.
If the main
method is found, it starts the execution of the Java code process.
To access any method, you can use the method name with an object (like object.method()).
We declare the main
method as static, signifying that the JVM can directly call the main
function using the class name, bypassing the need for object creation.
As a result, object creation is bypassed because the main
method is declared static.
The void
in the main method indicates that it returns nothing.
The public
keyword means it is accessible to all, implying that it can be accessed from outside all classes.
Strings Args[]
: arguments are command-line arguments for the Java class. You can set arguments through the command line as part of the Java tool to provide additional input while executing a Java program.
usage :- java javafilename argument1 argument2
The values argument1
and argument2
are available in the String args[] array once the execution starts with the above command.
Hence, main
method is declared static due to the these method always bind to class, not an object.