ADVERTISEMENT
ADVERTISEMENT

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...


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.