Why main() method is always static in Java?
Why main() method is always static in Java?
In Java, the main() method is always declared as static. Here the main() method is the entry point of a Java program and needs to be accessed without creating an instance of the class.
Few reasons why the main() method is always static in Java:
- Entry point: The
main()
method is the starting point of a Java program. It is the first method that is executed when a Java program runs. Since no object is created before executing themain()
method, it has to be declared as static so that it can be accessed without an object. - No need for object creation: In Java, a static method can be accessed without creating an object of the class. If the
main()
method were not declared as static, then we would need to create an object of the class in which themain()
method is defined before we could execute it. This would complicate the code and make it less efficient. - Consistent behavior: By making the
main()
method static, it ensures that the behavior of the method is consistent across all instances of the class. Since themain()
method is executed only once per program run, there is no need for it to depend on any instance variables or methods. - Ease of use: By making the
main()
method static, it is easier to call the method from outside the class. We can call themain()
method using the class name and the dot operator without creating an object of the class.
The syntax of the main() method includes several keywords and parameters:
- public: The public keyword is an access modifier that specifies that the main() method can be accessed from anywhere in the program.
- static: The
static
keyword is used to declare a method as a class method rather than an instance method. Since themain()
method is called without creating an object of the class, it must be declared as static. - void: The
void
keyword specifies that themain()
method does not return any value. In other words, themain()
method is not expected to return any output after execution. - main: main is the name of the method, which is a convention in Java.The method that will be called when the Java program is executed.
- String[] args: The
args
parameter is an array of strings that can be used to pass command-line arguments to the Java program. TheString[]
type specifies that theargs
parameter is an array of strings. By convention,args
is often used to pass command-line arguments to the Java program.
public static void main(String[] args) {
// code to be executed
}
Example program:
FileName: Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to my Java program!");
System.out.println("Command-line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
Output:
Welcome to my Java program!
Command-line arguments:
arg1
arg2
arg3