How to Exit Program in Java?

We have System.exit() method in java which is responsible for exiting the running program by terminating the JVM (Java Virtual Machine). In this blog, we will be learning about this exit method in a more detailed way along with suitable examples.

The exit method is available in the java.lang.System Class. Whenever we face an abnormal condition and it is necessary to terminate the program then we call this exit method.

Instead of throwing exceptions, we can use the exit method which tells the error present in the program.

System.exit() – Terminates Program or Method

exit() can take different parameters as an argument and it returns nothing since it is a void method. Here are the meanings of different arguments which can be passed in the exit method.

exit(0): Suggests that the program has been terminated successfully. Let us see the code written below for a better understanding.

Code:

Output:

Code Explanation:

In the above code, we are taking the age of some people inside the sample_array. Then we are creating a method named as ConditionMethod() which will terminate whenever there is a person age less than 18. A for loop is running across each element to check the condition, if it’s true then System.exit(0) is used to terminate the program instantly.

The exit() method can be used similarly with the try-catch block as well.

exit(1): Suggests that the program has not been terminated successfully

exit(-1): Suggests that the program has not been terminated successfully along with Exception

Remember that if we pass any other non-zero value as an argument then it will be considered an unsuccessful termination.

return Keyword – Terminates Method

There are more ways to terminate a method in java except using System.exit(). We can simply use the return keyword when a particular condition is reached.

Code:

Output:

The above code is almost the same as the previous code except that here we have used the return keyword to exit the method.

Please note here that exit() is used to terminate the whole program but the return keyword is used to terminate the method only.

I hope you were able to understand the ways to exit the java method clearly. Please do comment below if you are still having any doubts.

Leave a Comment

Your email address will not be published. Required fields are marked *