The System class in Java contains fields and methods to handle the SystemOne of them is the System.exit () method used in the Java language when you need to terminate a program or rather JVM instance that is currently running. Any line inserted below the exit method will be unreachable and will not be executed.
Syntax of System.exit() method
The syntax of the System.exit() method is as follows.
public void static(int status)
So you can see that it’s a static method. Actually, all the methods in System class are static methods. The exit() method takes an integer as an argument and returns nothing. So you will call the exit method as System.exit(i) where i is an integer. This integer is called “exit status” and can be a zero or non-zero element.
If the status is zero — exit(0), the program will have a successful termination. A non-zero status — exit(1) indicates abnormal termination of the JVM.Example of System.exit() method
Let’s see two simple examples of the exit() method with status as zero and non zero integers. In our first example, there is a loop over an array of colors. When the loop meets “green”, the application needs to be terminated.
import java.lang.*;
class Main {
public static void main(String[] args) {
String colors[]= {"red","blue","green","black","orange"};
for(int i=0;i<colors.length;i++) {
System.out.println("Color is "+colors[i]);
if(colors[i].equals("green")) {
System.out.println("JVM will be terminated after this line");
System.exit(0);
}
}
}
}
The following output will be displayed.The Terminal didn’t show any exit code in the output because we used zero as the status. As zero denotes successful termination, there is no need to print an exit code. So let’s use a positive integer as the status in our next example.
In this example, we create a loop that generates random numbers between 0 and 10. If the generated number is 2,3, or 7, the Application needs to be terminated, and it should print which number causes the termination. See the code below.
import java.lang.*;
import java.util.Random;
class Main {
public static void main(String[] args) {
System.out.println("program will be terminated when values are 2, 3, or 7");
int i;
Random number=new Random();
while(true){
i = number.nextInt(11);
System.out.println("Random Number is "+i);
if(i==2||i==3||i==7){
System.out.println("Value is "+ i + " your program will be terminated now");
System.exit(i);
}
}
}
}
When I executed the code, I got the following output.As you can see, number 3 caused the abnormal termination of the application. Now, let’s see how the status code can be used effectively.
GO TO FULL VERSION