How to terminate a Java Program

In this Java tutorial, we will talk about the ways to terminate a Java Program with example. Normally, we use the return statement in the main() method to exit the program. In this post, we will see how we can use the exit() method to do the same.

System.exit() in Java

This method terminates the running JVM (Java Virtual Machine) and hence terminates the current Java Program. The declaration for java.lang.System.exit() method has been shown below:

public static void exit( int status)

The status parameter is generally given as 0 for successful termination of the program and  -1 or 1( or any other non-zero value) for unsuccessful termination.

The return type for this function is void. Therefore, it does not return any value.

Please, go through the following example to understand the working of the exit() method.

import java.lang.*;

public class Main
{
  public static void main(String[] args) {
    int i=5;
    while(i>0)
    {
        System.out.println(i + "\n");
        i--;
    }
    if(i == 0)
    {
        System.exit(0);
    }
    System.out.println("This won't be executed as the program terminates already");
  }
}

Output:

5

4

3

2

1

Explanation:

In the example program, we are initializing a variable with value 5. Then we create a while loop that decrements the value of i by 1 in every iteration and prints it as long as it satisfies the given condition which states that its value must be positive. Then we have used an if statement which calls exit() method if the value of i is zero.

You can infer from the output that the last printing statement is not executed. That is because the exit() method has already been called and the program is terminated.

Thank you. I hope this post helped you gain some knowledge.

Also read: Java program to exit from a loop

Leave a Reply

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