Why main method is public static in java?
The main
method in Java is declared as public static
for specific reasons related to how the Java Virtual Machine (JVM) executes programs. Let’s break down these reasons and illustrate them with an example:
1. Accessibility:
public
: Themain
method needs to be accessible from outside the class, particularly from the JVM. By declaring it aspublic
, it can be accessed from any other class.
2. Static Context:
static
: Themain
method is called by the JVM before any objects are created for the class. This means the method needs to bestatic
so that it can be called without creating an instance of the class. Static methods belong to the class rather than to any specific instance of the class.
Here’s an example demonstrating the public static void main(String[] args)
signature and its usage:
Java
/*
* Author: Zameer Ali
* */
public class MainExample {
public static void main(String[] args) {
System.out.println("Hello, World!");
// Code inside the main method
}
}
main() Method divided into Several Parts
In this example:
public
: Makes themain
method accessible from outside the class. Without this keyword, other classes (specifically the JVM) wouldn’t be able to access and execute themain
method.static
: Allows themain
method to be called without creating an instance of theMainExample
class. When you run a Java program, you don’t create an object of the class with themain
method. Instead, you directly invoke the class through the command line, e.g.,java MainExample
, and the JVM calls themain
method without needing an instance of the class.void
: Indicates that themain
method doesn’t return any value.String[] args
: Represents the array of strings that can be passed as parameters when you run the Java program from the command line. For example, if you runjava MainExample arg1 arg2
,args
will be an array containing{"arg1", "arg2"}
.
By following this specific signature (public static void main(String[] args)
), Java provides a standardized entry point for executing programs, ensuring consistency and ease of use across different applications.