java 返回值,从Java代码返回值

本文解析了一个Java程序中,尽管主函数为`void`类型,但通过System.exit()指定返回值的情况。它解释了Java应用的退出机制与JVM进程的返回码,并提供了解决代码中实际返回值问题的方法。
摘要由CSDN通过智能技术生成

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值