Exit in Java
Here’s an idiomatic Java example demonstrating the concept of program exit:
public class ExitExample {
public static void main(String[] args) {
// This will not be executed due to the System.exit() call
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutdown hook will not be executed!");
}));
// Exit the program with status code 3
System.exit(3);
// This line will never be reached
System.out.println("This will not be printed!");
}
}
This Java program demonstrates the use of System.exit()
to immediately terminate the program with a specified status code. Here’s a breakdown of the code:
We define a public class named
ExitExample
.In the
main
method, we add a shutdown hook usingRuntime.getRuntime().addShutdownHook()
. This is similar to Go’sdefer
, but it’s important to note that shutdown hooks are not guaranteed to run when usingSystem.exit()
.We call
System.exit(3)
to immediately terminate the program with status code 3. This is equivalent to Go’sos.Exit(3)
.The last
println
statement will never be executed because the program exits before reaching this line.
To compile and run this program:
$ javac ExitExample.java
$ java ExitExample
To see the exit status in a Unix-like terminal:
$ java ExitExample
$ echo $?
3
On Windows, you can use %ERRORLEVEL%
instead of $?
to check the exit status.
Key points to note:
Unlike Go, Java does allow returning an integer from the
main
method to indicate the exit status. However,System.exit()
provides more control and can be called from anywhere in the program.Shutdown hooks in Java are similar to Go’s
defer
, but they are not guaranteed to run whenSystem.exit()
is called. This is why the message in the shutdown hook is not printed.Java’s
System.exit()
is more flexible than Go’sos.Exit()
as it can be called from any part of the program, not just themain
function.
This example demonstrates how to exit a Java program with a specific status code, which can be useful for indicating success or failure to external scripts or systems calling your Java program.