Question: Considering the standard java initialization order rules it is not clear to me why the following code

```
public class Foo {

    static { new Foo(); }

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

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

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

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

```

outputs this:

```
non static code
constructor
static code

```

Answer: 
So, the static block will execute as soon as the class loader loaded the class. So, your first static block `static { new Foo(); }` execute first which further calls the constructor `new Foo();`. As per the java [docs](https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html) the **non-static block will be copied to every constructor by the compiler** which means `System.out.println("non static code");` will be copied to the constructor `public Foo() { System.out.println("constructor"); }`. So, it will print `non static code` first then `constructor`. After the execution of first static block it will execute the second static block which prints the last `static code`.

After compilation your code looks similar to below code:

```
public class Foo {

    static { new Foo(); }

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

    public Foo() { 
       System.out.println("non static code");
       System.out.println("constructor"); 
    }

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

```
Well, to refactor the code, do the following steps:

1) remove non-static initialisation block - the compiler puts it **before** the code in the actual constructor

```
public class Foo {

    static { new Foo(); }

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

    public Foo() {
        System.out.println("non static code");
        System.out.println("constructor");
     }

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

```

2) Join static initialisation blocks - see [here](https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html):

> 
> A class can have any number of static initialization blocks, and they
>  can appear anywhere in the class body. The runtime system guarantees
>  that static initialization blocks are called in the order that they
>  appear in the source code.
> 
> 
> 

```
public class Foo {

    static {
        new Foo();
        System.out.println("static code");
     }

    public Foo() {
        System.out.println("non static code");
        System.out.println("constructor");
     }

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

```

3) From there, it should be obvious.