I know use System.exit(0) can end a java program, for instance, if I have a JFrame window, it will close and end the program, but I wonder how many other ways, can it be closed and the program be ended ? Including when an error occurs, will the program be shut down and the JFrame be closed ?
One other way the Java program ends is when the last statement in the java code is executed. Also when java.lang.OutOfMemory error occurs, the program terminates abnormally. This occurs when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
I've answered your question in the context of Swing GUIs given your mentioning of JFrame
.
- With a Swing GUI the Event Dispatch thread will log any exceptions that occur but will not terminate the application in this situation.
- Similarly, if another thread throws an exception and terminates the Event Dispatch thread will ensure that the application is kept alive (as it is not a daemon thread).
- One final point: If you wish your application to be terminated when a JFrame is closed, you need to call:
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Otherwise the frame will simply be hidden when you close it, but the application will continue to run.
Here's all I can think of off the top of my head:
main() returns (either a value or a void() main finishes executing its last statement)
program throws an exception uncaught
System.exit(int)
It can crash?
In your case of a JFrame closing, I believe there would be an onClose() handler which either calls System.exit(0) or causes the main method to return.
A Java program ends when the last Thread without daemon flag ends, or when you call a method that shuts down the virtual machine (System.exit(), Runtime.exit(), Runtime.halt() and possibly a few more).
Anything else is up to libraries that call System.exit() (such as a JFrame with EXIT_ON_CLOSE).
To add to other answers:
- If the process that is hosting the VM is forcefully terminated, your program will spontaneously disappear
- The same happens if the plug gets pulled on the machine hosting the VM :)
You can end a running Java program externally. By killing the java.exe process from task manager (in case of windows)