why main method is public static in java

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: The main method 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:
  • static: The main method is called by the JVM before any objects are created for the class. This means the method needs to be static 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

why main method is public static in java

In this example:

  • public: Makes the main method accessible from outside the class. Without this keyword, other classes (specifically the JVM) wouldn’t be able to access and execute the main method.
  • static: Allows the main method to be called without creating an instance of the MainExample class. When you run a Java program, you don’t create an object of the class with the main method. Instead, you directly invoke the class through the command line, e.g., java MainExample, and the JVM calls the main method without needing an instance of the class.
  • void: Indicates that the main 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 run java 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.

Leave a Reply

Your email address will not be published. Required fields are marked *