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()
1 2 3 4 5 6 7 8 |
public class ShutDownProgramExample1 { public static void main(String[] args) { System.out.println("Welcome to example one"); System.exit(1); System.out.println("This message wont get printed"); } } |
Running the above example will produce the following:
1 |
Welcome to example one |
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.
1 2 3 4 5 6 7 8 9 10 |
public class ShutDownProgramExample2 { public static void main(String[] args) { try { System.out.println("Welcome to example two"); System.exit(1); } finally { System.out.println("This message wont get printed"); } } } |
Running the above example will produce the following output:
1 |
Welcome to example one |
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.
1 2 3 4 5 6 7 8 |
public class ShutDownProgramExample3 { public static void main(String[] args) { Runtime.getRuntime() .addShutdownHook(new Thread(() -> System.out.println("This message will get printed"))); System.out.println("Welcome to example three"); System.exit(1); } } |
Running the final example produces the following:
1 2 |
Welcome to example one This message will get printed |
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
- How to read a property file
- How to split a String by new line
- Check if an array contains a certain value
- How to use callable in Java