Open In App

Static Block and main() Method in Java

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Example:

Java
// 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.");
    }
}




Output
Inside Static Block.
Inside main method.

Can we execute a Java class without declaring main() method?

The answer is 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:

Java
// without Main function but with static block

// 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 the above code gives an error in output.

Output: (JDK 1.7 onwards)

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

Static vs Instance Block in Java

Sometimes the query occurs if we have static block in Java then what is instance block. The difference lies between the functionality of both the concepts:

  • Static Block: Runs once when the class is loaded (before any object creation).
  • Instance Block: Runs every time a new instance is created (before the constructor is called).

Example:

Java
// static and instance block
import java.io.*;

class Geeks 
{
  	// static Block
  	static
    {
    	System.out.println("Static Block Called");	
    }
  	
  	// main method
    public static void main (String[] args) 
    {
      	// Object Created
      	Geeks obj = new Geeks();      
      	System.out.println("Main Method");
    }
  
  	// instance block
  	{
      	System.out.println("Instance Block Called");
    }
}

Output
Static Block Called
Instance Block Called
Main Method

Next Article
Article Tags :
Practice Tags :

Similar Reads