How To Exit A Program In Java?

Problem Analysis

Java is a high-level programming language and is machine-independent. Execution of programs in Java goes through a compiler and then through Java Virtual Machine. The Java Virtual Machine is not an independent operating system, but it is different for each operating system.

The source code of the java program is converted into bytecode. The compiler does this conversion. To convert the source code into a bytecode compiler builds the abstract syntax tree using the token sequence used in the program. Hence the symbol table is generated.

After this, the syntax tree is annotated by resolving names, bynducting type checking, and doing constant folding. The compiler then finds the program’s data flow and then finds the type of assignment done, and then finds the programming instruction reachability. When this process is done, the compiler generates a class file.

The class file is independent of the Operating System, making the machine independent. The Java virtual machine runs this class file. It is verified that all the variables declared in the java program are initialized, all the function calls are valid, all functions and data that are private are accessible, and the stack is maintained.

The just-in-time compiler of the java language converts the java program bytecode into machine code. The desired objective of the java program is achieved by executing initialization blocks and functions of the java program.

The objects of the class are initialized, and constructors are called each time a Java program is executed. Thus, the code in the initialization block is executed each time whenever the object of the class is created.

Java programs have a fixed execution cycle. The execution of the java program begins with the initialization block and is executed when the class is loaded in the java virtual machine. The execution order of the Code blocks of the java program is sequential, and the order they appear in the java program.

Classes of the java program are initialized. After class initialization, it is executed, and constructors are evoked. If there are more than two initialization blocks, the execution sequence of the code block is the order in which they appear in the source code.

Problem Description  

It is often required in java programming to break the execution sequence to achieve the desired objective. The execution sequence is altered based on condition or to terminate the java program. Thus it is required to have an understanding of how to terminate the java program.

Solution to Problem

Terminating the java program means terminating the Java Virtual Machine. To terminate the java program exit ( ) method is used. The exit ( ) method belongs to the system class, and system class belongs to the lang class, and lang class belongs to the java class; thus, it shares the following hierarchy – java.lang.System.exit ( ).

exit( ) is a parameterized method which can take an integer value. The integer value can be zero or non-zero. If the exit ( ) method contains the zero value then it conveys the message that program termination is successful. And if the exit ( ) method contains a non-zero value then program termination is unsuccessful.

The return type of the exit ( ) method is void since it does not return any value.

Following example explains the use of exit ( ) method.

Example Program to Understand exit ( ) method

import java.lang.*; 
public class Main
{
  public static void main(String[] args) {
    int i=6;
    while(i>0)
    {
    	System.out.println(i + "\n");
    	i--;
   
    	if(i == 2)
    	{
        	System.out.println("Program terminated at i = 2");
        	System.exit(0);
    	}
    }
  }
}
Output:
             	6
             	5
             	4
             	3
Program terminated at i = 2

Code Analysis

In this example java program, the integer variable i  is initialized to value 6. After variable initialization the while loop is created. The while loop has condition i > 0  this means that each time while loop is executed the condition i > 0 is checked if it is greater than zero then while loop is executed. Inside the loop the value if i  is decremented. This is done by executing following java statement:

i–; 

When the value of i is decremented then its value is checked inside the if statement. When the integer variable i  attains the value 2 then the java control goes inside the if statement. Inside the if statement java program termination statement is executed to terminate the java code. Following is the java program termination statement:

System.exit(0);

The system.exit(0) statement terminates the java program. This method is parameterized and has integer value 0 as parameter. 0 value signifies that the program terminated successfully.

Before the program gets terminated the message is displayed to the user about the value of i. The message contains the information that the program terminated since the integer variable i  has attained the value 2. This is done by executing the following code:

System.out.println(“Program terminated at i = 2”);

If this statement is placed after System.exit(0) then it will not be executed as the program will get terminated after executing System.exit(0).

Use of System.exit(0) program termination statement must be avoided as this thread invoking java language statement blocks and waits for the termination of JVM. This statement may also cause deadlock.

The main use of the System.exit(0) statement is to avoid abnormal conditions. This statement is used to terminate the program immediately and avoid abnormal conditions. This statement is also used to terminate the program outside of the main ( )  method that is terminating the program from the functions defined in the program.

Another example stating the use of system.exit(0):

import java.lang.*; 
public class Main
{
        	public static void main(String[] args)
        	{
                    	int b[]= {9,7,5,4,3,2,1}; 
                    	for(int i=0;i<b.length;i++) 
                    	{ 
                        	if( b[i] > 3 ) 
                        	{ 
                                  System.out.println("array["+i+"]="+b[i]+1); 
                         	} 
                         	else 
                         	{ 
                              	System.out.println(" I am terminating, I am exiting"); 
                                  System.exit(0); 
                          	}
                    	}	
          	}
}

Output
                  	array[0]=91
 
                  	array[1]=71
 
                  	array[2]=51
 
                  	array[3]=41
 
 I am terminating, I am exiting

Code Analysis

In the above program, an array is declared having name b, which can contain 7 elements. This program displays array elements after appending 1. Then, the array elements are displayed using a for loop. Inside the for loop there exists an if condition which compares the array element value with 3. If the array element value is greater than three, it displays the array element value after appending it with 1. But if the array element value is not greater than three, then part of the if statement is executed. In the other part, there are two statements: the first statement prints “I am terminating, I am exiting,” and the second statement terminates the program. The second statement is exit(0), and it is used to terminate the program.

Conclusion

System.exit( ) terminates the Java Virtual Machine and in turn terminates the currently running process. The parameter inside the exit ( ) function is passed to the operating system. The system.exit( ) can be placed anywhere in the java program depending on the logic of the program and the desired objective to be achieved.

System.exit ( ) terminates the program.