Search code examples
javacurly-bracesorder-of-execution

Curly braces only method


Why does Java accept a brackets only method? What is made for?

{
    // Do something
}

I also noticed that it is executed automatically after the static-block but before the constructor. Although the constructor of the super class is executed before.

Is there a specific reason for this order?

This is the JUnit I made for discovering the execution order:

public class TestClass extends TestSuperClass {

    public TestClass() {
        System.out.println("constructor");
    }

    @Test
    public void test() {
        System.out.println("test");
    }

    {
        System.out.println("brackets");
    }

    static {
        System.out.println("static");
    }
}

public class TestSuperClass {

    public TestSuperClass() {
        System.out.println("super class constructor");
    }

    {
        System.out.println("super class brackets");
    }

    static {
        System.out.println("super class static");
    }
}

As output I get:

super class static
static
super class brackets
super class constructor
brackets
constructor
test

Solution

  • It is the same as static block but just not static. So it will execute in the order that you already found out - after super constructor but before constructor. However, if static-block can be useful regular block not so much. So it is never used, but it is legal. I never saw it used and can not think of any particular purpose, but it is part of valid syntax. If it was not then static block wouldn't be either.