Thursday, October 9, 2025
HomeLanguagesJavaStatic Block and main() method in Java

Static Block and main() method in Java

In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading.

This is illustrated well in the following example:




// Java program to demonstrate that static 
// block is executed before main()
  
class staticExample {
  
    // static block
    static
    {
        System.out.println("Inside Static Block.");
    }
  
    // main method
    public static void main(String args[])
    {
        System.out.println("Inside main method.");
    }
}


One question arises from the above example:

Question: Can we execute a Java class without declaring main() method?
Answer: No since JDK 1.7 it is not possible to execute any java class without main() method. But it was one of the ways till JDK 1.6.
Example:




// The below code would not work in JDK 1.7
class staticExample {
  
    // static block execution without main method in JDK 1.6.
    static
    {
        System.out.println("Inside Static Block.");
        System.exit(0);
    }
}


Output:(In JDK 1.6)

Inside Static Block.

But from JDK 1.7 onwards the above code gives an error in output.

Output:

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

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32342 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6712 POSTS0 COMMENTS
Nicole Veronica
11876 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6833 POSTS0 COMMENTS
Ted Musemwa
7092 POSTS0 COMMENTS
Thapelo Manthata
6786 POSTS0 COMMENTS
Umr Jansen
6789 POSTS0 COMMENTS