exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination.
To end a Java program, we can use the exit() method of the System class. It is the most popular way to end a program in Java. System. exit() terminates the Java Virtual Machine(JVM) that exits the current program that we are running.
return; in your main() method.
You can use System.exit()
for this purpose.
According to oracle's Java 8 documentation:
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns normally.
The call
System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
System.exit(0);
The "0" lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1);
, or with another non-zero number corresponding to the specific error.
Also, as others have mentioned, clean up first! That involves closing files and other open resources.
System.exit(int i)
is to be used, but I would include it inside a more generic shutdown()
method, where you would include "cleanup" steps as well, closing socket connections, file descriptors, then exiting with System.exit(x)
.
System.exit()
is usually not the best way, but it depends on your application.
The usual way of ending an application is by exiting the main()
method. This does not work when there are other non-deamon threads running, as is usual for applications with a graphical user interface (AWT, Swing etc.). For these applications, you either find a way to end the GUI event loop (don't know if that is possible with the AWT or Swing), or invoke System.exit()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With