2 replies
by sushant Accepted solution
by Former member Accepted solution
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:
1. package net.cavdar.staticinitializer;
2.
3. /**
4. * Says "Hello World!" without main method. A simple use of
5. * static initialisation.
6. *
7. * @author accavdar
8. */
9. public class HelloWorldWithoutMain {
10. static {
11. System.out.println("Hello World!");
12. System.exit(0); // prevents "main method not found" error
13. }
14. }
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.
http://www.cavdar.net/2008/07/26/say-hello-world-without-main-method-in-java/
Please post back if you have any more problems or questions.
This discussion is closed to new replies.
Trending Software posts
Sort by Trending