In Java, you can terminate a program using the System.exit() method or by allowing the main method to naturally complete. The method you choose depends on the specific requirements of your program and how you want it to exit. Here's how you can do both:
1.Using System.exit():
The System.exit() method is used to forcefully terminate the Java program. You provide an exit status code as an argument to this method. Conventionally, an exit status code of 0 indicates a successful program execution, while any other non-zero code typically indicates an error or abnormal termination.
public class TerminateProgram {
public static void main(String[] args) {
// Your program logic here
// Terminate the program with a specific exit status code
System.exit(0); // Normal program termination
// System.exit(1); // Abnormal termination indicating an error
}
}
When you call System.exit(0), the program will immediately exit, and any code after this line in the main method will not be executed.
2.Allowing main to Complete:
By default, a Java program terminates when the main method reaches its end. You don't need to explicitly call System.exit() unless you encounter a situation where you want to terminate the program prematurely due to an error or other exceptional conditions.
public class TerminateProgram {
public static void main(String[] args) {
// Your program logic here
// Program will naturally terminate when the main method completes
}
}
In most cases, simply allowing the main method to complete is sufficient for normal program termination.
It's important to note that if you use System.exit(), you should use it with caution and only for exceptional circumstances, such as unrecoverable errors. Calling System.exit() should not be used as a regular way to exit a program, as it doesn't allow for proper cleanup of resources or finalization of tasks. Instead, you should structure your program logic to naturally complete when it has finished its intended tasks.
Exit Program
public class SystemDemo {
public static void main(String[] args) {
int arr1[] = { 0, 1, 2, 3, 4, 5 };
int arr2[] = { 0, 10, 20, 30, 40, 50 };
int i;
// copies an array from the specified source array
System.arraycopy(arr1, 0, arr2, 0, 1);
System.out.print("array2 = ");
System.out.print(arr2[0] + " ");
System.out.print(arr2[1] + " ");
System.out.println(arr2[2] + " ");
for(i = 0; i < 3; i++) { // Removed space before >=
if(arr2[i] >= 20) {
System.out.println("exit...");
System.exit(0);
} else {
System.out.println("arr2["+i+"] = " + arr2[i]);
}
}
}
}
Output
array2 = 0 10 20
arr2[0] = 0
arr2[1] = 10
exit...