java - what - why is the main() method declared static

return type of main in java (5)

I like to know why only void return type for main method in java.

public static void main(String [] args)

Why there is no other return types other than void for main method.


A reasonable middle way (between having a void signature, but also needing to return a value to the OS) to me then seems to be: To throw a Runtime exception in main for all return values that correspond to an error, with an appropriate message in that exception.

Of course, this helps only to differentiate between error and non-error exits at the OS level (say, a shell script etc.) but in many cases, this is actually all that is needed, and probably the most common use of these environment return values; either run or don't run the next command if this command fails.

Because you run main from JVM Hello.main, we can't return value to JVM. It simply gives run time exception.

It seems like an arbitrary decision, probably considering that not all operating systems are unixy in the sense that they allow a program to return an exit code.

Java could have been specified like C with an int return code from main. Multi-threading does not matter because there is only one thread that originally starts main and its return value could be the one to be returned to the OS by the JVM, regardless of when the other threads return and what they do.

This is far-fetched but if someone built a JVM that can run multiple Java programs each with its own main, it could be designed to return the value returned by the last main to be invoked.

The most reasonable rationale is that the JVM itself may need to return an exit code for reasons of its own, however, this rationale is belied by the provision of System.exit(int) which exactly overrides the JVM's return code. Given this, there is no reason to similarly allow main to return an int too, just as if the last thing that main did was System.exit(n)

All in all, sounds like an arbitrary decision.

Java specifies that an application entry point must be public static, named main, returns void, and takes a String[] as a parameter. This is just the way it is.

That said, you can technically define a main method that doesn't meet those criterias, but they won't be a valid application entry point.

public class MainMain {
    public static void main(String args[]) { // application entry point
    private static String main() {           // just a method named main
        return "Hello world!";

You should probably reserve main only for valid Java application entry points, but there's nothing preventing you from writing a code like the above.

What were you expecting to return?

In C you typically return an int exit code. However, in a multithreaded system this doesn't make much sense. Typically a Java program will start a number of threads. The main thread will often return more or less immediately.

System.exit can be used to exit with a specific exit code.