1. Anonymous block

An anonymous block in java is a special member of a class. It does not have names and represents statements that are common to all the constructors of the class. It has the following syntax:

{
    //statements common to all the constructor
}

An anonymous block is used when you want to execute some common statements before all the constructors that are available in a class.

class Demo{
	
	public Demo(){
		System.out.println("default constructor");
	}
	
		public Demo(int i){
		System.out.println("parameterized constructor");
	}
	
	{
		System.out.print("Object is created by the ");
	}
	
	public static void main(String arr[]){
		Demo b1 = new Demo();
		Demo b2 = new Demo(1);
	}
	
}

Output:

Object is created by the default constructor
Object is created by the parameterized constructor

As you can see the statement of the anonymous block is executed before the constructor. This happened because, at the time of compilation, statements of the anonymous block are moved to the beginning of each constructor by the compiler.

So after compilation, the above code looks like this

class Demo
{
    public Demo() {
        System.out.print("Object is created by the ");
        System.out.println("default constructor");
    }
    
    public Demo(final int n) {
        System.out.print("Object is created by the ");
        System.out.println("parameterized constructor");
    }
    
    public static void main(final String[] array) {
        final Demo demo = new Demo();
        final Demo demo2 = new Demo(1);
    }
}

You can verify this by decompiling the compiled source file using any of the online decompilers for java.

2. Static block

Static block is a special member of a class. It is implicitly invoked just after a class is loaded in the memory and it can be used to initialize static data members of a class. You can have multiple static blocks in a single class. It has the following syntax:

static {
      // statements to execute just after the class is loaded
}

Example:

class Demo{
	
	static {
		System.out.println("First static block is initialized");
	}
	
	static {
		System.out.println("Second static block is initialized");
	}
	
	public static void main(String arr[]){
	}
	
}

Output:

First static block is initialized
Second static block is initialized

The statement of the static block is initialized just after the class is loaded in the memory and the order of their execution is the same as the order in which they are written.

3. Conclusion

In this quick tutorial, we saw what are anonymous and static blocks and how to use them in java.