Beginner question about main
Hello everybody,
this is my first post about Java ever so be kind :D
I know C and C++ quite good i would say.However i decided that learning JAVA is a must for me.So i started with a tutorial i found on the net.The first question i had has been unresolved up to now,so i ask you
The question
Why function main has a void return type?In C and C++ it is int in order to notify if it has terminated sycceddfully or not.Why not the same in Java?Is there a reason?(maybe yes,else it would be the same i guess)
Re: Beginner question about main
There's some discussion from around the net:
Why is main() in java void? - Stack Overflow
Why does main() in java returns void ?
The main jist is because C/C++ were originally designed for single threaded applications. In these cases a program's end point should be when the main method returns.
However, in a multi-threaded application, the main method (and main thread) terminating does not necessarily mean the application has finished running. Thus, in these applications a main method return value simply does not make sense. This is the approach Java took from the beginning, even though not all Java applications must be multi-threaded.
This does not mean that a Java application cannot return a value, though. It simply means that a different mechanism is used.
In Java this is done using the System.exit() call.
Code java:
// somewhere in the code
if(DRAMATIC_ERROR)
{
System.exit(-1); // something went wrong
}
This call works by terminating all java threads and is guaranteed to be the end of your program (well, almost. There are a few caveats with shutdown hooks, finalization, and such).
There is also another option of calling System.halt() which forcibly terminates the JVM, meaning it is the absolute end of your program (or is close enough to it). However, under almost all circumstances it is recommend that you use System.exit() because it does allow shutdown hooks and other tasks to run.
Re: Beginner question about main
I think i got it.I do a little search for multi-threaded applications on the net though!So thank you :D