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.


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.

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.


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.

By admin

Leave a Reply

%d bloggers like this: