Tags: , , ,

Say “Hello World!” Without Main Method in Java

Can you print out “Hello World!” without writing a main method in Java? Think for a while. Yes, you’re right. It can be possible using “static initialization blocks”. Let’s see the source code first:

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 World” without writing a main method. The execution is stopped using “System.exit()” command. So, we prevent “main method not found” error. It is tricky. Isn’t it?

Happy coding. :D

Note: Write fully qualified class name (for our example “net.cavdar.staticinitializer.HelloWorldWithoutMain”) for configuring run options for main class, if you need.

Share and Enjoy:
  • del.icio.us
  • description
  • StumbleUpon
  • Digg
  • Technorati
  • Facebook
  • Reddit
  • TwitThis
  • Ma.gnolia
  • Mixx
  • Slashdot
  • Google
  • YahooMyWeb
  • Pownce

Related Posts

9 Responses to “Say “Hello World!” Without Main Method in Java”


  1. 1 jj

    is this about learning java basics ? :)

  2. 2 onotole

    [:|||:]

  3. 3 Nice trick

    Trick is nice but what are you trying to preach; can it ever be used in real life scenario.

  4. 4 Veera

    Nice trick!

  5. 5 Abdullah Cetin CAVDAR

    Here, I use the traditional “Hello World” example to demonstrate the usage of “static initializer blocks”. More meaningful and detailed example can be found in the link below:

    The Essence of OOP using Java, Static Initializer Blocks

    Thank you all for your nice comments. :D

  6. 6 abhi

    It doesn’t work ! :)

  7. 7 Abdullah Cetin CAVDAR

    What is the problem Abhi?

  8. 8 tugrul

    just like old procedural languages
    good old days!!

  9. 9 Kamal

    Yes, you can print this. But static initializer is useful for initializing resources/variables shared by all instances of a class.

Leave a Reply




View Abdullah Çetin ÇAVDAR's profile on LinkedIn

Join My Community at MyBloglog!

Add to Technorati Favorites

Subscribe To My FriendFeed!

My Facebook Profile

E-Mail Subscriptions

Enter your email address:

My Flickr Photos

www.flickr.com

My Recent Readers