How exactly works the Java application exit code of the main() method?
The VM exits when
- all of the non-daemon threads stop running, or
System.exit(exitCode)
is called
In the first case, the exit code is 0. In the second case, it's the exit code passed to the exit()
method.
Don't forget that even if your main() method returns, the program will continue running until no non-daemon thread runs anymore. And any thread running in the VM can choose to exit explicitely.
The exit code 0 means that everything went as expected. you can choose to use any other exit code to signal an exceptional condition to the environment.
Exit code of process is what process reports to operating system as its error code.
Java designers could make main()
method to return int
so that JVM could report to OS this value as a process exit code. But they decided to make main void but provide API that can update this code using System.exit(exitCode)
. The advantage of this solution is that program can decide to exit at any point and in any thread, not only in main method and in main thread.
An exit code of 0 means it completed normally, that is standard for all processes, not just java. The value is not returning from the main method (it's void) but from the JVM itself.
A different value can be specified, e.g. System.exit(1)
to indicate some error condition, and the program stops.