views:

370

answers:

7

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

+10  A: 

Using System.exit()?

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#exit(int)

Jon
+4  A: 
System.exit(0);

If you want to be a command-line-savvy java-weenie. =)

The "0" lets whoever 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 especially closing files.

Chris Cooper
I thought it was System.exit(1) ?
AFK
I believe that generally 0 means success. But this may be system-dependant. I'm not sure.
Chris Cooper
+1  A: 

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
Freiheit
+2  A: 

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

Christian Semrau
+1  A: 

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

Bastien
A: 

This post might be what you want if you are trying to programmatically exit a GUI app:
http://stackoverflow.com/questions/1234912/how-to-programmatically-close-a-jframe

orange80
A: 

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.

Vaishak Suresh