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:

  1. We define a public class named ExitExample.

  2. In the main method, we add a shutdown hook using Runtime.getRuntime().addShutdownHook(). This is similar to Go’s defer, but it’s important to note that shutdown hooks are not guaranteed to run when using System.exit().

  3. We call System.exit(3) to immediately terminate the program with status code 3. This is equivalent to Go’s os.Exit(3).

  4. 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:

  1. 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.

  2. Shutdown hooks in Java are similar to Go’s defer, but they are not guaranteed to run when System.exit() is called. This is why the message in the shutdown hook is not printed.

  3. Java’s System.exit() is more flexible than Go’s os.Exit() as it can be called from any part of the program, not just the main 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.