Core Java

Java System.exit() Example

In this article we want to explain the Java System.exit method in Java.

1. Syntax and functionality of the Java System.exit

The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code as an argument. Following is the syntax for java.lang.System.exit() method:

public static void exit(int status)

1.1 Parameters

status − This is the exit status.

exit(0) : means a normal exit.
exit(1) or exit(-1) or any other non-zero value – means an abnormal exit.

Now lets see Example01 to understand it better:

Exit class

public class Exit {

    public static void main(String[] args)
    {
        String arr[] = {"It", "is", "time", "to", "exit"};

        for (int i = 0; i < arr.length; i++)
        {
            if (arr[i].equalsIgnoreCase("exit"))
            {
                System.out.println("exit...");

                // Terminate JVM
                System.exit(0);
            }
            else
                System.out.println(arr[i] + " ");
        }
        System.out.println("End of Program");
    }
}

Output is:

It 
is 
time 
to 
exit...

When we call the System.exit the subsequent code after the System.exit is effectively unreachableand yet, the compiler does not know about it.

System.exit(0);
System.out.println("This line is unreachable");

It’s not a good idea to shut down a program with System.exit(0). Because it gives us the same result of exiting from the main method and also stops the subsequent lines from executing, also the thread invoking System.exit blocks until the JVM terminates. If a shutdown hook submits a task to this thread, it leads to a deadlock.

2. When to use System.exit() ?

Actually when there is an abnormal condition and we need to exit the program immediately.

Also, if we have to terminate the program from a place other than the main methodSystem.exit is one way of achieving it.

Also a script can rely on the exit codes of commands it invokes. For example, instead of throwing an exception, we can return an abnormal exit code that can then be interpreted by the calling script.

Now lets see Example02:

ReadFile class

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("myFile.txt"));
            System.out.println(br.readLine());
            br.close();
        } catch (IOException e) {
            System.out.println("Exiting using System.exit()");
            System.exit(-1);
        } finally {
            System.out.println("Exiting the program");
        }
    }
}

Output is:

Exiting using System.exit()

In this example, we tried to read a file. If the file does not exist, we exit the program with System.exit() from the catch block. Please note that the finally block does not get executed if the file is not found. Because the System.exit() on the catch block exits the JVM and does not allow the finally block to be executed.

So as you see usage of System.exit() method suit better for script-based applications or wherever the status codes are interpreted. This is a convenient way to handle shutdown in bigger programs, where all parts of the program can’t (and shouldn’t) be aware of each other. Then, if someone wants to quit, he can simply call System.exit(), and the shutdown hooks (if properly set up) take care of doing all necessary shutdown ceremonies such as closing files, releasing resources etc.

3. Download the Source Code

Download
You can download the full source code of this example here: Java System.exit() Example

Firouzeh hejazi

A self-motivated and hard-working developer with more than 4 years of extensive experience in developing software in java platforms. A multi-skilled and problem-solving engineer who has participated in implementing a range of applications in different roles. Possess a MSc in Knowledge Engineering and Decision Science.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button