- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is System.exit() in Java?
This method belongs to the System class of the java.lang package. It terminates the current JVM (Java Virtual Machine).
This method accepts an integer value representing the status code, it accepts two values 0 or, 1 or, -1. Where, 0 indicates a successful termination and 1 or, -1 indicates an unsuccessful termination.
Example
Following program accepts an array of elements from the user and prints the it. While printing if any of the given elements is greater or equal to 20 the program exits.
import java.util.Scanner; public class System_Exit_Example { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created ::"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array (below 20):"); for(int i=0; i<size; i++){ myArray[i] = sc.nextInt(); } System.out.println("Printing the array ....."); for(int i = 0; i < myArray.length; i++) { if(myArray[i] >= 20) { System.out.println("exit..."); System.exit(0); } else { System.out.println("arr2["+i+"] = " + myArray[i]); } } } }
Output
Enter the size of the array that is to be created :: 4 Enter the elements of the array (below 20): 11 12 5 20 Printing the array ..... arr2[0] = 11 arr2[1] = 12 arr2[2] = 5 exit...
Advertisements