There is a Java class which creates a POST request and sends it to a servlet. The main method of the class file (test) looks something like this:
public static void main(String[] args) throws IOException {
// Code logic goes here...
// No return Statement
}
This is called from a KornShell (ksh) script something like this:
retcode=`$CLK_JAVA_PATH -cp $CLASSPATH test ${PASSWORD} ${HOSTNAME} ${TOOLSET}`
if [ $? != "0" ];then
echo "ERROR:
echo "${retcode}"
else
echo "${SCRIPT} Success"
fi
retcode
always has the value "2" independent of if the code fails or succeeds.
My question is since the return type of my main method is "void" why is the code returning some value?
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.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'smain
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 toSystem.exit()
will be used as the return value of the JVM process on most OS.So ending your
main()
method with this:will ensure two things:
main
is reached andYou're not getting the exit status, that's what
$?
contains. You're getting standard out, whatever is written toSystem.out
.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 callingSystem.exit(code);
, for example:Use
this will give your app control over the return value seen by the OS.
This returns error code 0 (everything went fine). System.exit Doc