为什么java中的main()无效? [英] Why is main() in java void?
问题描述
对于具有类似C语法的语言,我们声明main()方法返回int或float值(或void)。是否可以从Java中的main()声明非void返回类型?如果没有,那么为什么不呢?这是否意味着Java程序不会向操作系统返回任何值?
In the case of languages with a C-like syntax, we declare the main() method to return an int or float value (or void). Is it possible to declare a non-void return type from main() in Java? If not, then why not? Does this mean that a Java program doesn't return any value to the OS?
推荐答案
main ()
方法必须确实具有 void
返回类型。来自 Java语言规范的执行 - 虚拟机启动(§12.1.4 ):
The main()
method must indeed have a void
return type. From the Java Language Specification on "Execution - Virtual Machine Start-Up" (§12.1.4):
方法
main
必须声明为
public
,static
,void
。它必须
接受一个
字符串数组的参数。
The method
main
must be declaredpublic
,static
, andvoid
. It must accept a single argument that is an array of strings.
它继续描述何时程序退出执行 - 程序退出(§12.8 ):
It goes on to describe when a program exits in "Execution - Program Exit" (§12.8):
一个程序终止其所有活动
和退出
发生两件事:
A program terminates all its activity and exits when one of two things happens:
- 所有不是
守护程序线程的线程终止。 - 某些线程
调用类
的退出
方法运行时$
安全管理器不禁止c $ c>或类系统
和退出
操作。
- All the threads that are not daemon threads terminate.
- Some thread
invokes the
exit
method of classRuntime
or classSystem
and the exit operation is not forbidden by the security manager.
换句话说,程序可以在 main
方法完成之前或之后退出;因此, main
的返回值将毫无意义。
如果您希望程序返回状态代码,请调用以下方法之一(请注意,所有三种方法都不会正常返回):
In other words, the program may exit before or after the main
method finishes; a return value from main
would therefore be meaningless.
If you want the program to return a status code, call one of the following methods (note that all three methods never return normally):
-
System.exit(int status)
- 相当于Runtime.getRuntime()。exit(status)
-
Runtime.exit(int status)
- 通过启动其关闭序列来终止当前运行的JVM(运行所有已注册的 shutdown hooks 和 uninvoked finalizers ,如有必要)。完成此操作后,JVM将暂停。 -
Runtime.halt(int status)
- 强行终止当前运行的JVM。
System.exit(int status)
- Equivalent toRuntime.getRuntime().exit(status)
Runtime.exit(int status)
- Terminates the currently running JVM by initiating its shutdown sequence (run all registered shutdown hooks, and uninvoked finalizers, if necessary). Once this is done the JVM halts.Runtime.halt(int status)
- Forcibly terminates the currently running JVM.
在这三者中, System.exit()
是终止JVM的传统且最方便的方法。
Of the three, System.exit()
is the conventional and most convenient way to terminate the JVM.
这篇关于为什么java中的main()无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!