Friday, March 15, 2019

Java System exit() Method

Java System exit() Method

The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.
  • Note: Status - exit(0) - indicates Successful termination
  • Status - exit(-1) - indicates unsuccessful termination with Exception
  • Status - exit(1) - indicates Unsuccessful termination

Syntax

  1. public static void exit(int status)  

Parameter

status - It is the exit status.

Returns

This method does not return any value.

Exception

If security manager exist and his checkexit method doesn't approve exit with specified status then a SecurityException is thorwn.

Example 1

  1. import java.lang.*;  
  2. public class SystemExitExample1 {  
  3.   
  4.     public static void main(String[] args) {  
  5.         int a[]= {9,8,7,6,5,4,3,2,1};  
  6.         for(int i=0;i<a.length;i++)  
  7.         {  
  8.             if(a[i]>5)  
  9.             {  
  10.             System.out.println("array["+i+"]="+a[i]);  
  11.             }  
  12.             else  
  13.             {  
  14.                 System.out.println("terminating jvm,exiting");  
  15.                 System.exit(0);//Treminatejvm  
  16.             }  
  17.         }  
  18.     }  
  19. }  
Test it Now
Output:
array[0]=9
array[1]=8
array[2]=7
array[3]=6
terminatingjvm,exiting

Example 2

  1. public class SystemExitExample2 {  
  2.   
  3.     public static void main(String[] args) {  
  4.         System.out.println("program will terminate when i is 1");  
  5. for(int i=10;i>0;i--)    {         
  6. System.out.println("your no is "+i);  
  7. if(i==1){  
  8. System.out.println("Value is 1 now terminating your program");  
  9. System.exit(1); //exit program  
  10.             }  
  11.             }  
  12.     }  
  13. }  
Test it Now
Output:
program will terminate when i is 1
your no is 10
your no is 9
your no is 8
your no is 7
your no is 6
your no is 5
your no is 4
your no is 3
your no is 2
your no is 1
Value is 1 now terminating your program

No comments:

Post a Comment