静态块是否在没有main方法的情况下执行? [英] Will a static block execute without the main method?

查看:157
本文介绍了静态块是否在没有main方法的情况下执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我给出了一个Java测验,并且有一个问题:

Today I have given a Java quiz, and there was a question like:


静态块甚至在应用程序中没有main方法执行程序。

1.正确
2.错误

The static block even executed without main method in application program.
1. True
2. False

我已经回答了问题为 2。假。但是,在检查了我的结果后,我感到困惑,因为根据测验,这是错误的答案。现在,我用我自己的示例代码重新检查了我的答案,它没有执行任何操作也没有显示任何错误。这是我的示例代码:

I've answered the question as 2. False. But, after checking my result I was puzzled out, because it was the wrong answer as per the quiz. Now, I've rechecked my answer with my own sample code and it doesn't execute anything nor show any errors. Here's my sample code:

public class StaticBlockDemo {
    static {
        System.out.println("Hello World");
    }
}

哪一个是正确答案?我正在使用Java 7.

Which one is the right answer? I'm using Java 7.

推荐答案

如果你放一个 System.exit(0) static -block的末尾,它将在Java 6及更低版本中运行时没有错误(没有有效的 main !)。这是因为在搜索有效的 main 方法之前, c> static 块被执行,因此,如果在静态块结束时退出程序,则不会收到任何错误。

If you put a System.exit(0) at the end of the static-block, it will run with no errors in Java 6 and below (without a valid main!). This is because the static block is executed before a valid main method is searched for, so if you exit the program at the end of the static block, you will receive no errors.

然而,这种行为在Java 7中已经改变;现在你必须包含一个明确的 main ,即使它可能永远不会到达。

However, this behavior was changed in Java 7; now you must include an explicit main, even if it might never be reached.

在Java 7中,问题的答案是 false ,但在Java 6及以下答案是确实 true

In Java 7, the answer to the question is false, but in Java 6 and below the answer is indeed true.

public class Test {
    static {
        System.out.println("Hello World");
        System.exit(0);
    }
}

Java 6:


Hello World

Java 7:


Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)

这篇关于静态块是否在没有main方法的情况下执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆