How to execute a static block without main method in Java?

VM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.


public class Sample {
   static {
      System.out.println("Hello how are you");

Since the above program doesn’t have a main method, If you compile and execute it you will get an error message.

C:\Sample>java StaticBlockExample
Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

If you want to execute static block you need to have Main method and, static blocks of the class gets executed before main method.


Live Demo

public class StaticBlockExample {
   static {
      System.out.println("This is static block");
   public static void main(String args[]){
      System.out.println("This is main method");


This is static block
This is main method

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started