[java] How to quit a java app from within the program

What's the best way to quit a Java application with code?

This question is related to java

The answer is


The answer is System.exit(), but not a good thing to do as this aborts the program. Any cleaning up, destroy that you intend to do will not happen.


System.exit() will do what you want. But in most situations, you probably want to exit a thread, and leave the main thread alive. By doing that, you can terminate a task, but also keep the ability to start another task without restarting the app.


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(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.


This should do it in the correct way:

mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowListener() {

@Override
public void windowClosing(WindowEvent e) {
    if (doQuestion("Really want to exit?")) {
      mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainFrame.dispose();
    }
}

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().


Runtime.getCurrentRumtime().halt(0);

System.exit(ABORT); Quit's the process immediately.


There's two simple answers to the question.

This is the "Professional way":

//This just terminates the program.
System.exit(0);

This is a more clumsier way:

//This just terminates the program, just like System.exit(0).
return;

Using dispose(); is a very effective way for closing your programs.

I found that using System.exit(x) resets the interactions pane and supposing you need some of the information there it all disappears.


I agree with Jon, have your application react to something and call System.exit().

Be sure that:

  • you use the appropriate exit value. 0 is normal exit, anything else indicates there was an error
  • you close all input and output streams. Files, network connections, etc.
  • you log or print a reason for exiting especially if its because of an error