Computer Applications

What is the significance of System.exit(0)?

Java Conditional Stmts

47 Likes

Answer

The function System.exit(0) is used when we want to terminate the execution of the program at any instance. As soon as System.exit(0) function is invoked, it terminates the execution, ignoring the rest of the statements of the program.

Syntax:

System.exit(0);

For example, if I am writing a program to find the square root of a number and the user enters a negative number then it is not possible for me to find the square root of a negative number. In such situations, I can use System.exit(0) to terminate the program. The example program to find the square root of a number is given below:

import java.util.Scanner;
public class SquareRootExample {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int n = in.nextInt();
        if (n < 0) {
            System.out.println("Cannot find square root of a negative number");
            System.exit(0);
        }
        double sqrt = Math.sqrt(n);
        System.out.println("Square root of " + n + " = " + sqrt);
    }
}

Answered By

16 Likes


Related Questions