System.exit() in Java

Filed Under: Java
System.exit() in java

The System.exit() method terminates the Java virtual machine. This method takes an argument, which is the status code passed to the caller.

A status code of zero signifies a normal exit whereas a status code of non-zero signifies an abnormal code.

The code is not so important within Java itself. However, it’s common for scripts to rely on the exit codes of commands it invokes.

Several non-zero codes can mean several different types of exits. This enables programmers to design their response system accordingly.

The System.exit() is like a harsh version of breaking out of loops using conditionals.

System.exit() with status code 0

Let’s write a for loop and use System.exit(0) to exit out of the program with a status code of 0.

public class Main {

    public static void main(String[] args) {

        for(int i=0;i<10;i++){
            System.out.println(i);
            if(i>5){
                System.exit(0);
            }
        }
    }
}
System Exit Code 0
Output
0
1
2
3
4
5
6

Process finished with exit code 0

We can see that the program terminates with an exit code of 0.

Exiting with a non-zero status code

We can exit out of the program with any non zero exit code.

public class Main {

    public static void main(String[] args) {

        for(int i=0;i<10;i++){
            System.out.println(i);
            if(i>5){
                System.exit(10);
            }
        }
    }
}
System Code Non Zero

You can see that the exit code is printed as 10 in the output.

When to use System.exit()

It’s useful when you are calling a Java program from shell script. You can terminate the program in case of an abnormal scenario and pass on the status code to the caller shell script.

Conclusion

That is how Java.lang.System.exit() works. It is common to use it to exit loops and functions. Interestingly enough, System.exit() if not placed properly can render a certain portion of your code unreachable.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages