English
Follow Us Online
Twitter    YouTube(TM)
Declare a variable
Declare a String
Declare an Array
Declare constants
Define enum
Define a method
Exit program
Exit a for loop
Exit a method
Format date
Format double
Find current directory
Get current date
Get user input
Get Class name
Java How to A B C D E F G H I J K L M N O P Q R S T U V W Y W Z
Java How to exit program
Related Links Exit program Exit for loop Exit a method Next Page >>>
Steps:
  1. System class's exit method terminates the JVM.
  2. It takes status code as the argument.
  3. Status code of zero means normal termination.
  4. System.exit() in turn calls Runtime class's exit method. That is, Runtime.getRuntime().exit()
 /**
 * Example Class demonstarting How to exit program
 * 
 * @author www.f5java.com
 */
class Exitprogram {
	// Example method exiting the program
	public void exitMethodExample() {
		System.out.println("Before exit is called");

		// 1. Invoke exit method of the System class
		System.exit(0); // 2. Program will exit after executing this statement

		System.out.println("After exit is called"); // 3. This will never get executed
	}
}     
Java How to exit for loop
Notes:
  1. When break statement is encountered within a loop, it'll stop the iteration completley & exits the loop.
  2. Usually You check for some condition to be true or false to stop looping and exit the for loop.
/**
 * Example showing how to exit for loop
 * 
 * 
 * @author www.f5java.com
 * @return : void
 */
public void exitForLoopExample() {
	System.out.println("Exit for loop after printing a message 3 times");

	for (int i = 0; i < 5; i++) { // 1. Looping begins
		System.out.println(i + "> Inside for loop");
		
		if (i == 2){ // 2. Condition to break out of for loop
			break; // 3. breaks out of the loop 			
		}			
	}
	System.out.println("Out of for loop");
}
     
Java How to exit a method
Notes:
  1. By default, a method exits when execution reaches the end.
  2. One more way is to use return statement which is also used to return a value.
  3. throw statement also exits from a method.
/**
 * Example showing how to exit method using return statement
 * 
 * @author www.f5java.com
 * @return : boolean
 */

public boolean exitMethodExample1() {
	boolean isValid = false;
	return isValid; // 1. return statement always exits a method
}

/**
 * Example showing how to exit method
 * 
 * @author www.f5java.com
 * @return : boolean
 */
public void exitMethodExample2() {
	String  firstName = "Joe"; 
	System.out.println("First Name ::" + firstName); // 1. control exits after the execution of this line	
}