You’ve written a Java program, but you’re not sure how to exit it. Don’t fret. We will show you all the common ways that you can use to exit a Java program. You will learn how to terminate a Java application using System.exit(), returning from the main method, and other approaches. Each method we cover comes with sample code and explanations to help you understand when and how to use them effectively.
Table of contents
System.exit()
The System.exit(int status) method is the most direct way to terminate a Java program. This method has a status parameter to indicate the exit status. By convention, a status of 0 indicates that a Java program has terminated normally, while any nonzero status code, such as 1 or -1 indicates an abnormal termination.
The following example demonstrates how to use System.exit():
public class ExitExample {
public static void main(String[] args) {
System.out.println("Learning Java is fun!");
// Some code logic here
// Exiting the program with status 0 (normal termination)
System.exit(0);
// This line will never be executed
System.out.println("This will not be printed.");
}
}Code language: Java (java)
The output for the above program is this:
Learning Java is fun!
Process finished with exit code 0Code language: Bash (bash)
Learn Java like a pro! Check out our complete course that helps you master the Java fundamentals.
In this example, the program prints a message and then terminates using the exit() method of the System class. Notice that any code that follows the System.exit() call will not be executed and essentially becomes unreachable code. We also see that the program terminated with exit code 0, which is a successful termination.
Return from the main method
Returning from the main method is perhaps the simplest way to exit a program, especially when you want to terminate the program after completing certain tasks. You will find that this approach is cleaner and more graceful compared to System.exit() that we saw earlier.
This simple example shows how to use a return statement to terminate a program:
public class ReturnExample {
public static void main(String[] args) {
boolean terminate = true;
System.out.println("Learning Java is fun!");
// Some code logic here
// Exiting the program by returning from main method
if (terminate) {
return;
}
// This line may or may not be executed
System.out.println("This line may not be printed.");
}
}Code language: Java (java)
Output:
Learning Java is fun!Code language: Bash (bash)
In this example, the program prints a message and then exits the main method using return, causing the program to terminate. The program will only end prematurely if the value of terminate remains true. If that value is changed to false, we would see the last print statement in the console.
Return to the main method from another method
Another way to exit a program in the Java language is by returning from methods called by the main method. This is useful when you have multiple methods and want to terminate the program based on certain conditions evaluated within those methods.
Here’s how to do it:
public class ReturnFromMethodExample {
public static void main(String[] args) {
System.out.println("Learning Java is fun!");
if (!performTask()) {
System.out.println("An error has occurred.");
return;
}
System.out.println("Task completed successfully.");
}
public static boolean performTask() {
// Some code logic here
// Returning false to indicate failure and exit the program
return false;
}
}Code language: Java (java)
Output:
Learning Java is fun!
An error has occurred.Code language: Java (java)
In this simple program, the performTask() method returns false to the calling method, which is main. The if statement in main evaluates the return value, and the program is terminated.
The Java Virtual Machine (JVM) terminates a program when the main method returns because the main method is the application’s entry point. When the main method completes, the JVM assumes that the program has finished executing.
Throw an exception
Lastly, we will look at how to exit a Java program by throwing an exception. This is generally not recommended for normal program termination but can be useful in certain error conditions.
The following code uses this method:
public class ExceptionExample {
public static void main(String[] args) {
System.out.println("Learning Java is fun!");
try {
// Perform some operations
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
if (i == 2) {
throw new RuntimeException("Exiting due to an error at count 2.");
}
}
// This line will be executed only if no exception is thrown
System.out.println("Loop completed. Program ending.");
} catch (RuntimeException e) {
System.err.println(e.getMessage());
}
// Any cleanup code can be placed here if needed
System.out.println("Cleanup if necessary before exiting.");
}
}Code language: Java (java)
Output:
Learning Java is fun!
Count: 0
Count: 1
Count: 2
Cleanup if necessary before exiting.
Exiting due to an error at count 2.
Process finished with exit code 0Code language: Bash (bash)
In this last example, the program starts, performs a simple loop, and throws an exception when the count reaches 2. Notice that since the exception is caught and handled, the program exits with code 0, but we could have also thrown an unhandled exception. Also, note that any necessary cleanup code is executed before the program terminates.
Final thoughts on terminating Java programs
As we have seen in this article, multiple ways exist to exit a program in the Java programming language, each suitable for different scenarios. For instance, we looked at Java code that used System.exit(int status) to immediately terminate the program with a specific status code. One can also more gracefully exit a program by calling the return statement in the main method and using a conditional termination based on results in methods that are called from the main method. Lastly, we saw how to exit a program by throwing an exception.
Don’t miss these
Follow our blog
Be the first to know when we publish new content.
- How to Exit A Program in Java - June 16, 2024
- How to Get User Input in JavaScript - June 7, 2024
- How To Calculate Percentage In Java - June 1, 2024