Why main method is public static in java?
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:
mainmethod needs to be accessible from outside the class, particularly from the JVM. By declaring it as
public, it can be accessed from any other class.
2. Static Context:
mainmethod is called by the JVM before any objects are created for the class. This means the method needs to be
staticso 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:
main() Method divided into Several Parts
In this example:
public: Makes the
mainmethod accessible from outside the class. Without this keyword, other classes (specifically the JVM) wouldn’t be able to access and execute the
static: Allows the
mainmethod to be called without creating an instance of the
MainExampleclass. When you run a Java program, you don’t create an object of the class with the
mainmethod. Instead, you directly invoke the class through the command line, e.g.,
java MainExample, and the JVM calls the
mainmethod without needing an instance of the class.
void: Indicates that the
mainmethod 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 run
java MainExample arg1 arg2,
argswill be an array containing
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.