Friday, 8 July 2016

Why is main() in java void?

Java was designed from the beginning to be a multithreaded environment.

Reason of void return of main method:

1. The reason for the main method having void as return type is that once main finishes, it doesn't necessarily mean that the entire program finished. If main spawns new threads, then these threads can keep program running. The return type of main doesn't make much sense at this point.

Example:
This is very common in Swing applications, where the main method typically starts a GUI on the Swing thread, and then main finishes however the program is still running.

2. The program may exit before or after the main method finishes; a return value from main would therefore be meaningless. If you want the program to return a status code, call one of the following methods (note that all three methods never return normally):

System.exit(int status) - Equivalent to Runtime.getRuntime().exit(status).

Runtime.exit(int status) - Terminates the currently running JVM by initiating its shutdown sequence (run all registered shutdown hooks, and uninvoked finalizers, if necessary). Once this is done the JVM halts.

Runtime.halt(int status) - Forcibly terminates the currently running JVM.

Why C and C++ allowed int return type? 
C and C++ were both designed as languages before multithreading was a widely known technique, and both had threads grafted onto them at a later date (main can return int in C and C++).


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...