Return value from a Java code

。_饼干妹妹 提交于 2019-12-03 22:30:23

The return value of a Java application is not the return value of it's main method, because a Java application doesn't necessarily end when it's main method has finished execution.

Instead the JVM ends when no more non-daemon threads are running or when System.exit() is called.

And System.exit() is also the only way to specify the return value: the argument passed to System.exit() will be used as the return value of the JVM process on most OS.

So ending your main() method with this:

System.exit(0);

will ensure two things:

  • that your Java application really exits when the end of main is reached and
  • that the return value of the JVM process is 0

Java programs do not return an exit code back to the operating system by returning a value from main, as is done in C and C++. You can exit the program and specify the exit code by calling System.exit(code);, for example:

// Returns exit code 2 to the operating system
System.exit(2);
Jacob
System.exit(0);

This returns error code 0 (everything went fine). System.exit Doc

Use

System.exit( someNumber );

this will give your app control over the return value seen by the OS.

Your program always returns a return code after exiting. In normal programs, if you do not specify a return code, it will return zero (this includes setting the return type to void).

Java, however, likes to be special! Java won't return the return code you return at the Main method, but it'll return some return code when the JVM exits (this accounts for multithreaded programs), and will return what a System.Exit(returnCode); call specifies.

You're not getting the exit status, that's what $? contains. You're getting standard out, whatever is written to System.out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!