. Advertisement .
..3..
. Advertisement .
..4..
This article demonstrates all of the best ways to utilize the Java exit program for terminating a running program. We’ll go over a few scenarios to help you grasp the problem as well as the most feasible methods to deal with it.
Ways To Terminate A Java Exit Program
System.exit() To Terminate A Java Program
There are several ways to end a program in Java for someone who doesn’t know how. To begin, we may utilize the System class’s exit() method, which is, by far, the most popular way to terminate a Java application.
System.exit() ends the Java Virtual Machine (JVM), which terminates the current program. To help you grasp it better, below is a fundamental example of how to cease a Java application using the System.exit() function.
It is important to note, however, that this feature requires an integer, which is the status code. Then we call the exit() method with a value of 0, indicating that the termination went off without a hitch.
A non-zero status, such as 1 or -1, signals the compiler that the program should be terminated with an error or message. Furthermore, in the example below, you can see that the output only prints Statement 1.
Statement 2 was never able to be performed since the program exited after its execution.
Running the code:
public class Main {
public static void main(String[] args) {
System.out.println("Object 1");
System.exit(0);
System.out.println("Object 2");
}
}
Output:
Object 1
Exit A Java Method Using Return
In Java, the exit() method is the easiest way to halt a program in abnormal circumstances. The return keyword can also be used to quit a Java program.
Once the return keyword is used, it completes the method’s execution and returns the function’s value. When a method does not return any value, the return keyword can be advantageous to quit it. Let’s have a look at an example:
Running the code:
public class Main {
public static void Calculate(int numberA, int numberB) {
if (numberA > numberB)
return;
int Result = numberA - numberB;
System.out.println(Result)
}
public static void main(String[] args) {
Calculate(22, 28);
Calculate(12, 29);
Calculate(19, 2);
}
}
Output:
-6
-17
SubMethod accepts two inputs, num1 and num2, and subtracts num2 from num1 in the following program, returning the result in the response variable. However, there is one condition: num2 must not be bigger than num1, which is done using an if conditional block.
If this condition is true, the if block with the return statement will be executed. Because SubMethod is of the void type in this scenario, return returns null and so ends the function.
Conclusion
The procedure regarding ways to conduct a Java exit program is outlined above. Hopefully, you’ll be able to get some further helpful data. Best of luck to you!
Leave a comment