How do I terminate a Java application?

In an application we sometimes want to terminate the execution of our application, for instance because it cannot find the required resource.

To terminate it we can use exit(status) method in java.lang.System class or in the java.lang.Runtime class. When terminating an application we need to provide a status code, a non-zero status assigned for any abnormal termination.

package org.kodejava.lang;

import java.io.File;

public class AppTerminate {
    public static void main(String[] args) {
        File file = new File("config.xml");

        int errCode = 0;
        if (!file.exists()) {
            errCode = 1;
        }

        // When the error code is not zero go terminate
        if (errCode > 0) {
            System.exit(errCode);
        }
    }
}

The call to System.exit(status) is equals to Runtime.getRuntime().exit(status). Actually the System class will delegate the termination process to the Runtime class.

Running the code give the following output because it can’t find the config.xml file.

Process finished with exit code 1