Tag Archive for 'static-initialization'

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.


RSS Feed

Digg It!

Add to Del.cio.us

Stumble It!

Add to Technorati Favorites

Add to Reddit



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