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.
Note: Write fully qualified class name (for our example “net.cavdar.staticinitializer.HelloWorldWithoutMain”) for configuring run options for main class, if you need.
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |











is this about learning java basics ?
[:|||:]
Trick is nice but what are you trying to preach; can it ever be used in real life scenario.
Nice trick!
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.
It doesn’t work !
What is the problem Abhi?
just like old procedural languages
good old days!!
Yes, you can print this. But static initializer is useful for initializing resources/variables shared by all instances of a class.
your code is a bit buggy, please test on several different platforms, before posting, kthxbye
package net.cavdar.staticinitializer;
/**
* Says “Hello World!” without main method. A simple use of
* static initialisation.
*
* @author accavdar
*/
public class HelloWorldWithoutMain {
static {
System.out.println(”Hello World!”);
// you need the next line to avoid ClassNotFoundException
new HelloWorldWithoutMain();
System.exit(0); // prevents “main method not found” error
}
}
Hi kajastancos,
I run it for Windows, Fedora Linux and Sun Solaris operating systems without any modification and any problem. I checked it once more for you.
Thanks for your comment and interest.
It seems meaningless to say that static initialization is just a trick or it can’t be used in a real life scenario.
It’s a common way to load libraries -though alternatives- when using jni.
thank you very much i desperately need it