How exactly does the Java application exit code of the main () method work?

I have the following doubts about a simple Java command-line application.

So, I have this command line application that is launched using the main () method defined inside the Main class.

As usual, this main () method is defined by this signature:

public static void main(String[] args) { 

So the return type is void . Therefore, this should mean that it does not return any value.

But why, when its execution finishes correctly, do I get this message in the IntelliJ console?

 Disconnected from the target VM, address: '127.0.0.1:54090', transport: 'socket' Process finished with exit code 0 

What exactly is exit code 0 ?

I think this means that the program completed its execution correctly without introducing any errors.

So now I have the following two doubts:

  • If this is true, why does this happen if my main () method returns void ?

  • How can I return a different exit code if my application fails? Is there a default exit code value for error completion?

Tpx

+8
java java-ee main exit-code
source share
3 answers

VM comes out when

  • all non-daemon threads stop working or
  • System.exit(exitCode) is called

In the first case, the exit code is 0. In the second case, the exit code is passed to the exit() method.

Do not forget that even if your main () method returns, the program will continue to run until a non-daemon thread is executed. And any thread running in the virtual machine can explicitly choose the output.

Exit code 0 means that everything went as expected. you can use any other exit code to signal an exceptional state of the environment.

+15
source share

The output code of a process is what the process reports to the operating system as an error code.

Java designers could make a main() method to return an int so that the JVM can tell the OS this value as the process exit code. But they decided to make the main void, but provide an API that can update this code using System.exit(exitCode) . The advantage of this solution is that the program can decide to exit at any time and in any thread, not only in the main method and in the main thread.

+3
source share

Exit code 0 means that it completed normally, which is standard for all processes, and not just for java. The value is not returned from the main method (it is not valid), but from the JVM itself.

You can specify a different value, for example. System.exit(1) to indicate some error condition, and the program stops.

+3
source share

All Articles