Run a Java Program with no Main method!!!

heya! 🙂

I happened to find something really interesting…

Have you ever wondered running a simple console-based java program without a main method???

Well, its possible! It’s a trick actually, but worth a try! 🙂

Try running this…

public class NoMain {
static {

It is done using “static initialization blocks”.

So, what is “static initializer block”?

  • A static initializer block is defined using the keyword static.
  • The code in a static initializer block is executed once by the virtual machine when the class is loaded.
  • A static initializer block cannot contain a return statement. Therefore, no need to specify a return type.
  • A static initializer block doesn’t have an argument list.
  • It can initialize only static data members of the class.

Because the static initializer block is executed when the class is first loaded, we can print out “Hello” without writing a main method. The execution is stopped using “System.exit()” command. So, we prevent “main method not found” error.

Wow!!! 🙂


aishwarya 🙂 🙂



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s