【问题标题】:Why java's main method should not have a return value? [duplicate]为什么java的main方法不应该有返回值? [复制]
【发布时间】:2012-11-10 13:37:34
【问题描述】:

可能重复:
Where and why JVM checks that the return type of entry method main(String args[]) is void and not anything else?
return type of main in java

在咨询了What's the meaning of the return value of int main(), and how to display it?&What should main() return in C and C++?这两个问题后,我想出了另一个问题:

为什么Java程序的main方法应该返回void,而C/C++程序的main函数应该返回int?

【问题讨论】:

  • 简单地说,Java 程序不会因为main 方法(在主线程上运行)结束而结束。 当所有线程结束时结束。所以main的返回值没有意义。

标签: java


【解决方案1】:

Java 规范:

方法 main 必须声明为 publicstaticvoid。它必须接受一个字符串数组的单个参数。

还有:

当以下两种情况之一发生时,程序会终止其所有活动并退出:

  • 所有非守护线程的线程都会终止。
  • 某个线程调用RuntimeSystem类的exit方法,安全管理器不禁止exit操作。

如您所见,由于其他线程的退出,主返回类型可能毫无意义。

【讨论】:

  • 问题是为什么,而不是什么。
  • @UniMouS:因为它是这样定义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 2020-12-31
  • 2012-10-23
  • 2011-11-15
  • 1970-01-01
相关资源
最近更新 更多