With respect to C/C++ main() must always return an integer(zero to indicate success and non-zero to indicate failure). I can understand this as the program is run it becomes a process and every process should have an exit status, which we obtain by doing echo $? from shell after the process gets over.
Now I don’t understand why is the main method does not return anything in Java? Has it got anything to do with the fact that the program is run on JVM and the JVM process is reposnsible for the returning of exit status?
Please clarify.
Thanks,
Roger
If the main method of a single threaded java application terminates, the application will terminate with exit code 0. If you need another exit code, maybe to indicate an error, you can place
anywhere in the code (especially outside of the main method).
This is different for multi-threaded applications
, where you either have to useSystem.exitfrom the inside ofkill -9from the outside to stop the JVM.Here’s a quick example where termination of main doesn’t stop the application (a typical service or daemon behaviour):
Remark: Sure, a thread will terminate when it’s run method (or the main method in case of the main thread) terminates. And in this case, when all threads have terminated, the JVM will terminate with exit code 0 (which brings us back to the initial question). Hope everybody is happy now.