Some Bits in Few Pieces
Print "Hello World" in Java
public class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}


Pretty Simple. Rite!! Well.. yeah. So whats the catch?

Can we do it without the main function??

How could we? Thats not possible. The execution begins from the main function only, how can anything be executed before that?

If you think this way, you are absolutely correct. Till 5 minutes ago i too was correct in the same way. But then came Static Blocks. Check this out -

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


It does work. It prints Hello World!!!. The exclamation marks do signify the amusement that i felt. :)

Static blocks are a facility provided in java language for executing some statements before our application starts executing from the main.

Ideally these blocks are used for initializing static variables. We can do the bulk initialisation in here, to reduce the code size and complexity. But in addition to this sort of simple initialisation, the code can attain any complexity.

To Quote from http://www.developer.com -

"A static initializer block resembles a method with no name, no arguments, and no return type. It doesn't need a name, because there is no need to refer to it from outside the class definition. The code in a static initializer block is executed by the virtual machine when the class is loaded.

Like a constructor, a static initializer block cannot contain a return statement. Therefore, it doesn't need to specify a return type.

Because it is executed automatically when the class is loaded, parameters don't make any sense, so a static initializer block doesn't have an argument list."

Syntax -

Simple as ABC, jus include whatever code you want inside a static block.

static {
...
}


And all the code would be executed as such before the main is called.

Cheers :)