Java中的main方法可以返回一些东西吗? [英] Can a main method in Java return something?
问题描述
我最近接受了一次采访,他们在核心Java中问我两个问题。
I went through an interview recently and they ask me two questions in core Java.
问题1。
我们可以编写一个java类:
Can we write a java class with:
public static int main(String[] args){
System.out.println("Hello");
我回答:不。编译器不会将其编译为它期望 main
的返回类型为 int
,尽管我们可以重载它。
I answered: No. The compiler won't compile it as it is expecting the return type of main
to be int
, though we can overload it.
问题2:下一个我无法回答的问题。
Q 2: The next question I was unable to answer.
编写一个程序以便你的Java
main
方法可以返回一些东西。
Write a program so that your Java
main
method could return something.
即怎么能让 public static void main([] args)
返回一些东西?
I.e. how can you make public static void main([] args)
to return something?
任何人都可以帮我回答这个问题吗?
Can any body help me to answer this?
推荐答案
Q 1.我们可以写吗一个java类,包含:public static int main(String [] args){
Q 1. Can we write a java class with : public static int main(String[] args){
是的,你可以但是你不能运行它Java类。
Yes, you can but you can't run that Java class.
示例类:
class MainTest {
public static int main(String[] args) {
return 1;
}
}
尝试运行时会收到错误消息:
You will receive an error message when trying to run it:
Error: Main method must return a value of type void in class MainTest, please
define the main method as:
public static void main(String[] args)
问题2:下一个问题我无法回答。他要求写一个程序,所以
你的java主方法可以返回一些东西。
Q 2: Next question I unable to answer. He asked write a program so that your java main method could return something.
你可以使用 System#exit(int)退出您的程序具有可由操作系统解释的特定退出代码。
You can use System#exit(int) to quit your program with a specific exit code which can be interpreted by the operating system.
这篇关于Java中的main方法可以返回一些东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!