Terminating a Java Program

Calling System.exit(0) (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java process will return to the operating system. You can make this call from anywhere in your program – and the result will always be the same – JVM terminates. As this is simply calling a static method in System class, the compiler does not know what it will do – and hence does not complain about unreachable code.

return statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void (as in your example), then you do not need to specify a value, as you’d need to return void. If the method is declared to return a particular type, then you must specify the value to return – and this value must be of the specified type.

return would cause the program to exit only if it’s inside the main method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:

public static void main(String... str) {
    System.out.println(1);
    return;
    System.out.println(2);
    System.exit(0);
}

will not compile with most compiler – producing unreachable code error pointing to the second System.out.println call.

Leave a Comment