Understanding “static” in “public static void main” in Java


In Java, "static" is a keyword that is used to define a class-level variable or method. When a variable or method is declared as static, it belongs to the class rather than to any instance of the class. This means that the variable or method can be accessed without creating an object of the class.

In the context of "public static void main", "static" is used to define the main method of a Java program. The main method is the entry point of the program, and it is called by the Java Virtual Machine (JVM) when the program is executed.

Here is an example of the "public static void main" method:

public class MyProgram {
    public static void main(String[] args) {
        // code to be executed when the program is run
    }
}

In this example, "MyProgram" is the name of the class, and "main" is the name of the method. The "public" keyword indicates that the method can be accessed from outside the class. The "static" keyword indicates that the method belongs to the class rather than to any instance of the class. The "void" keyword indicates that the method does not return a value.

There are a few other things to note about the "public static void main" method:

  • The method must be declared as "public" so that it can be accessed by the JVM.
  • The method must be declared as "static" so that it can be called without creating an object of the class.
  • The method must be named "main" so that the JVM knows where to start executing the program.
  • The method must take an array of strings as its parameter, which is used to pass command-line arguments to the program.

Overall, the "public static void main" method is a crucial part of any Java program, as it is the entry point for the program and allows it to be executed by the JVM.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.