Page 343 - CITS - Computer Software Application -TT
P. 343
COMPUTER SOFTWARE APPLICATION - CITS
1
2
3
5
1
2
3
5
2
3
5
Terminate a Java program
What is exit() Method in Java?
Java provides exit() method to exit the program at any point by terminating running JVM, based on some condition
or programming logic. In Java exit() method is in java.lang.System class. This System.exit() method terminates
the current JVM running on the system which results in termination of code being executed currently. This method
takes status code as an argument.
Uses
• exit() method is required when there is an abnormal condition and we need to terminate the program
immediately.
• exit() method can be used instead of throwing an exception and providing the user a script that mentions what
caused the program to exit abruptly.
• Another use-case for exit() method in java, is if a programmer wants to terminate the execution of the program
in case of wrong inputs.
Syntax of exit() in Java
public static void exit(int status)
Parameters of exit() in jJava
System.exit() method takes status as a parameter, these status codes tell about the status of termination. This
status code is an integer value and its meanings are as follows:
• exit(0) - Indicates successful termination
• exit(1) - Indicates unsuccessful termination
• exit(-1) - Indicates unsuccessful termination with Exception
Note: Any non-zero value as status code indicates unsuccessful termination.
Return Value for exit() in Java
As the syntax suggests, it is a void method that does not return any value.
Exit a Java Method using System.exit(0)
As mentioned earlier, System.exit(0) method terminates JVM which results in termination of the currently running
program too. Status is the single parameter that the method takes. If the status is 0, it indicates the termination
is successful.
Let’s see practical implementations of System.exit(0) method in Java.
Example 1
Here is a simple program that uses System.exit(0) method to terminate the program based on the condition.
330
CITS : IT&ITES - Computer Software Application - Lesson 85 - 93