Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from a Java code

Tags:

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?

like image 526
Monojeet Avatar asked Jul 21 '11 12:07

Monojeet


People also ask

What does values () return in Java?

The Java HashMap values() method returns a view of all the values present in entries of the hashmap. Here, hashmap is an object of the HashMap class.

Can a class return a value in Java?

It is possible, but you need to change your code a bit.


2 Answers

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
like image 193
Joachim Sauer Avatar answered Nov 12 '22 21:11

Joachim Sauer


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); 
like image 45
Jesper Avatar answered Nov 12 '22 21:11

Jesper