Sunday, December 18, 2011

Static Block of a Class

This post intended to be a quite quick. So let's begin. Could you tell me the output of the code written below?


public class EmptyClass {

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

}

There can be following options
A. It will not compile.
B. It will compile but it will not run and it will just print exception.
C. It will compile and it will not run but it will print "Hello World" and then will print the exception.
D. It will compile and Run without issues.

After seeing the choice, answer looks quite simple. Is not it?
Anyways lets analyze.
A. It will compile as static blocks are allowed in java and java does not force you to write main method in each and every class. So there are not any issues while compiling the class. So A is not the right option.

B. It will not run, true. As java says, there should be main method to run an application. There is not any run method is the application. But there is a static block in the application. What will happen to this static block? This options seems to correct but puzzle has not completely solved yet. Lets move forward and see if B is correct or there is any other better option available.

C. We accept it will compile but it will not run as main method is not available in the class or JVM. But as java say, before as soon as it loads any class in memory it executes all its static blocks first. So to run the application class will be loaded into the memory so static block exists in the class will executed which in turn will print "Hello World". So it seems to be most appropriate answer.

D. Do we have any scope and requirement left to discuss last options. No

I learnt this lesson while discussing few basic java questions with my friend. Nice but tricky is not it... Anyways will stop here. B bye.

1 comment: