How to quit a Java program

In this post we will provide a few examples of how to quit a Java program using System.exit(). In general all Java applications will terminate once all threads have finished there executions. If for some reason you wish to terminate an application you can use System.exit().

How to quit a Java program

As per documentation System.exit(n) where n is the exit code:

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

Example 1

The first example is very simple showing what happens when you use System.exit()

Running the above example will produce the following:

As you can see from the output, the second print statement was not executed.

Example 2

The second example, wraps the System.exit() in a try/finally block to see if the finally block is executed.

Running the above example will produce the following output:

As you can see from the output, the finally block was never executed.

Example 3

The final example will use a ShutDown hook, to run some logic before the system is terminated.

Running the final example produces the following:

As you can see, the shutdown hook is executed. This is good to know if you want any logic to be executed before the application is terminated.

Similar posts

  1. How to read a property file
  2. How to split a String by new line
  3. Check if an array contains a certain value
  4. How to use callable in Java

References

  1. Java 8 System.exit API Documentation

Leave a Reply