Question: Just wondering about the reason of compiling code like this:

```
class MyClass extends AnotherClass {
  {
    MySecondClass object = new MySecondClass();
    object.doSomething();
  }
}

```

Whats the difference between this code and code in constructor? This code executes **before** the object creation.

Answer: 
The code inside the braces with no names will be part of the constructor of the class and be executed before the logic contained in the class constructor.

Quick example:

```
public class Foo {
    {
        System.out.println("Before Foo()");
    }

    public Foo() {
        System.out.println("Inside Foo()");
    }

    {
        System.out.println("Not After Foo()");
    }
}

```
This is called an *instance initializer.* The code in the initializer is inserted *after* the call to the super class constructor and *before* the rest of the constructor code.

The first operation of any constructor is to invoke a super class constructor. If a constructor is called explicitly, `super(...)`, the specified constructor is used. If no constructor is explicitly invoked, the default constructor (with no arguments) is invoked in the super class. If no such constructor exists, it is a compile time error.

After this explicit or implicit constructor invocation, instance initializers are invoked in the order they appear in source code (yes, you can have more than one initializer).

To illustrate, running this program prints 

```

Another constructor
Init 1
Init 2
Test constructor

```

```
class Another {
  Another() { System.out.println("Another constructor"); }
}

class Test extends Another {

  public static void main(String[] args) { new Test(); }

  { System.out.println("Init 1"); }

  Test() { System.out.println("Test constructor"); }

  { System.out.println("Init 2"); }

}

```

The most commonly seen application is in the initalization the ["double brace initialization" idiom,](https://stackoverflow.com/questions/1372113/meaning-of-new-class-initialization-idiom/1372124#1372124) where an anonymous inner class is defined, and an instance is created and configured at once. Here's a fairly common example from Swing programming:

```
JButton popupButton = new JButton(new AbstractAction("Popup") {
  {
    putValue(Action.SHORT_DESCRIPTION, "Popup a dialog");
  }

  @Override
  public void actionPerformed(ActionEvent evt)
  {
    popup();
  }
});

```

This could be useful if you have multiple constructors, and need to perform some parameter-less initialization in every constructor. This could be factored into an initialization block.