Skip to content

Terminating a Java Program

There are several ways to terminate a Java program, depending on the context in which the program is running.

If you want to terminate a standalone Java program that is running in a console, you can use the System.exit() method. This method terminates the currently running Java Virtual Machine (JVM).

For example:


java
public class Main {
    public static void main(String[] args) {
        // Some code here
        System.exit(0);  // Terminate the program
    }
}

The System.exit() method takes an integer argument, which is the exit code of the program. A value of 0 indicates that the program terminated successfully, while a non-zero value indicates that the program terminated with an error.

Keep in mind that the System.exit() method is a "violent" way to terminate a program, and it may not give other threads or resources a chance to clean up before the JVM exits. To allow graceful cleanup, you can register shutdown hooks using Runtime.addShutdownHook().

If you want to terminate a program that is running in a GUI, you can configure the main window to exit the JVM when closed. In Swing, this is typically done by calling setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) on the JFrame instance. Note that calling dispose() alone only closes the window; the JVM will continue running if non-daemon threads are still active.

For example:


java
import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My Program");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.