Java - Demonstrate Example of System.exit() Method using Java program.
IncludeHelp
09 September 2016
In this program (code snippet) we will learn how to exit/ terminate on any situation condition from current java program?
System.exit() is a method which is used to terminate java program, while using this method we can pass either 0 r -1; 0 represents successful termination while -1 represents unsuccessful termination.
In this program, we are reading and printing integer values until -1 is not entered. When user input will be -1 program will be terminated, otherwise program will print entered number.
Java Code Snippet - Example of System.exit() in Java
//Java - Demonstrate Example of System.exit() Method using Java program.
import java.util.Scanner;
class JavaExitExample
{
public static void main(String args[])
{
int number=0;
Scanner SC=new Scanner(System.in);
while(true){
System.out.print("Enter an integer number (-1) to exit: ");
number=SC.nextInt();
if(number==-1){
System.out.println("Bye Bye...");
System.exit(0); //exit program
}
//print number otherwise
System.out.println("Number is: "+number);;
}
}
}
Enter an integer number (-1) to exit: 10
Number is: 10
Enter an integer number (-1) to exit: 20
Number is: 20
Enter an integer number (-1) to exit: 0
Number is: 0
Enter an integer number (-1) to exit: 40
Number is: 40
Enter an integer number (-1) to exit: 50
Number is: 50
Enter an integer number (-1) to exit: -1
Bye Bye...