What is the Difference Between public static void main(String[] args) and public static void main()?

What is the Difference Between public static void main(String[] args) and public static void main()?

In the Java programming language, the public static void main(String[] args) method serves as the primary entry point for a Java application, allowing for command-line argument handling. Conversely, public static void main() is a non-standard entry point that does not conform to the standard expected by the Java Virtual Machine (JVM).

Standard Entry Point: public static void main(String[] args)

The public static void main(String[] args) method is the standard entry point for a Java application. When the JVM is invoked to run a Java program, it searches for this method signature to identify the main method. The String[] args parameter allows the program to accept command-line arguments, providing the program with the ability to handle user input from the command line.

Example Usage

Here's an example of how to use the public static void main(String[] args) method to process command-line arguments:

public class MyProgram {
    public static void main(String[] args) {
        for (String arg : args) {
            (arg);
        }
    }
}

Non-standard Entry Point: public static void main()

The public static void main() method is a non-standard entry point that does not conform to the JMM expectations. As a result, the JVM will not recognize it as the main entry point for the application. If you try to run a Java program with this method, it will fail to ute.

Example Usage

Here's an example of a non-standard main method:

public class MyProgram {
    public static void main() {
        // Here you can write code, but this method cannot accept any command-line arguments
    }
}

To uate this method, you would have to call it from another method like the standard main(String[] args) with String[] args, which is not typical for Java applications.

Storing Command Line Arguments in String Array Type

If you are running a program through the command line and want to store command line arguments, you do so in a String[] args array. Each command-line argument input is stored in an index of this array, allowing you to access them later using their index number. For example, if you run a program called Hello from the command prompt with the following command:

To compile: javac 
To run: java Hello 1 2 3 4 5

You can then access the command-line arguments as follows:

args[0]  1
args[1]  2
args[2]  3
args[3]  4

Conclusion

In summary, public static void main(String[] args) is the required method signature for the main entry point of a Java application, allowing for command-line arguments. On the other hand, public static void main() is a non-standard method that cannot serve as an entry point for a Java application.

Keywords: Java main method, command-line arguments, Java Virtual Machine (JVM)