Site icon TestingDocs.com

Terminate a Java Application

Overview

Normally the java program terminates when the main method finishes the execution. Sometimes, we need to terminate the Java application from the code. For example, we may want to terminate the Java application if the user chooses to the Quit menu option, etc. To terminate a Java application, we can use System.exit(statusCode) method.

System.exit(statusCode)

exit() method is a static method in the System class. This method terminates the currently running JVM. We can pass an argument as the status code to this method. A zero status code implies normal termination. A non-zero status code implies abnormal JVM termination.

For example,

System.exit(0) method to terminate a Java application or program gracefully.

This is equivalent to the following line of code:

Runtime.getRuntime().exit(0);

Every Java application has a single instance of the class Runtime. We can interface with the environment using the Runtime instance.

Note that: The Java application cannot create the instance of the class. To get the current runtime we need to rely on and invoke the getRuntime() static method on the Runtime class.

 

public class TerminateJavaApplication {

	public static void main(String[] args) {
		System.out.println("Good Bye!");
		System.exit(0); //Terminate JVM
		System.out.println("Unreachable");
	}
}

 

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version