Open In App

System.exit() in Java

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the System.exit() method is present in the java.lang package. This method is used to explicitly terminate the currently running Java program. This method takes a status code. A non-zero value of the status code is generally used to indicate abnormal termination. When this method is invoked then we cannot perform any further tasks.

  • This method takes a single argument, the status code. If it is 0, then it indicates that the termination is completed.
  • If a non-zero status code is passed, then it shows the termination is unsuccessful for reasons like abnormal behaviour of the program or any exception.

Syntax of System.exit() Method

public static void exit(int status)

  • Parameter: It takes a single argument, the status, which is generally a zero or non-zero value.
  • Return Type: This method does not return anything but exits the current program.
  • Exception: This method might throw SecurityException if a security manager is present and the exit() operation is restricted.

Example: Using the System.exit() method to exit the currently running program.

Java
// Java program to demonstrate working of System.exit() 
import java.util.*; 
import java.lang.*; 

public class Geeks
{ 
	public static void main(String[] args) 
	{ 
		int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; 

		for (int i = 0; i < arr.length; i++) 
		{ 
			if (arr[i] > 4) 
			{ 
				System.out.println("exit..."); 

				// Terminate JVM 
				System.exit(0); 
			} 
			else
				System.out.println("arr["+i+"] = " + 
								arr[i]); 
		} 
		System.out.println("End of Program"); 
	} 
} 

Output
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
exit...

Explanation: In the above Java code, we use the exit() if the element is greater than 4 in the array, then we call the exit(0) with a status code as 0 and after that the program successfully exits.

Note: Use System.exit() carefully, specially in large applications, because it stops the JVM immediately.



Next Article
Article Tags :
Practice Tags :

Similar Reads