Java System.exit() Method

Java System.exit() Method with Examples

In this article, I am going to discuss Java System.exit() Method with Examples. Please read our previous article where we discussed the Java Calendar class.

Java System.exit() Method

To terminate the program in between based on some condition or program logic, Java provides exit() that can be used to terminate the program at any point.

In Java, exit() method is in the java.lang.System class. This method is used to take an exit or terminating a running program. It can take either zero or non-zero value. Basically, exit(0) is used for successful termination, and exit(1) or exit(-1) is used for unsuccessful termination. The exit() method does not return any value.

Example:

In this program, we are terminating the program based on a condition and using the exit() method.

import java.util.*;
import java.lang.*;
public class ExitMethodDemo
{
    public static void main (String[]args)
    {
        int x[] = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };

        for (int i = 0; i < x.length; i++)
        {
         if (x[i] >= 40)
         {
             System.out.println ("Program is Terminated...");
             System.exit (0);
         }
         else
             System.out.println ("x[" + i + "] = " + x[i]);
        } 
    }
}

Output:

Java System.exit() Method with Examples

In the next article, I am going to discuss How to work with JSON in Java with Examples. Here, in this article, I try to explain Java System.exit() Method with Examples. I hope you enjoy this Java System.exit() Method with Examples article.

Leave a Reply

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