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.
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |











Recent Comments