Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

java - Will a static block execute without the main method?

I'm trying to run the below code on my machine, but it didn't execute anything nor showing any errors.

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

Can someone please help me? By the way, I'm using Java 7.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...