Vijin Paulraj Vijin Paulraj - 25 days ago 21
Java Question

Will a static block execute without main method?

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


The static block even executed without main method in application program.

1. True

2. False


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");
}
}


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

Answer

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)
Comments