Java's System.exit(0) is like C++'s exit(0) in that
- It terminates the process
- It can be called from anywhere in the program.
The latter point makes it an “unstructured” control-flow construct that academic types tend to frown on. (In this case, they've got a good reason: If a function reports a failure via an exception (or old-fashioned return code), it's possible for the caller to recover from the error, but exit burns that bridge. Of course, sometimes errors do need to be treated as fatal.)
In C++, return 0 is equivalent to exit(0) if it's in the main function. (In other functions, it doesn't mean anything special.)
The relevant different between C++ and Java here is the return type of main.
- In C++,
main must return int. Normally, this would mean that it must have a return statement, but the C++ standard makes main a special case with an implied return 0; as the end if you don't write one.
- In Java,
main must return void.
In C++, it's common to write return statements in main, even though it's technically redundant, for stylistic consistency with all the other non-void functions in your program.
In Java, you can't return the exit code from main because it's a void function. So, if you want to explicitly specify an exit code, you have to use System.exit.
It's not wrong to end every Java main function with System.exit(0), but it's just not idiomatic to do so unless you've got a construct like
public static void main(String[] args) {
try {
//... do the work
System.exit(0);
} catch (Throwable t) {
//... report the error
System.exit(1);
}
}