Question: The compiler shows an error at `new Stock[2];` after `;{` expect.

```
public class TestStockUI {
    Stock[] stock = new Stock[2];
    stock[0] = new Stock("Microsoft", "MSFT", 15.69);
    stock[1] = new Stock("Google", "GOGL", 323.98);

    public TestStockUI() { }

}

```

Then I have changed it like below resulting in the same error.

```
public class TestStockUI {
    Stock[] stock = new Stock[2];
    stock[0] = new Stock("Microsoft", "MSFT", 15.69);
    stock[1] = new Stock("Google", "GOGL", 323.98);

}

```

This solve the problem but I don't know why.

```
public class TestStockUI {
    Stock[] stock = new Stock[2];
    {
        stock[0]=new Stock("Microsoft","MSFT",15.69);
        stock[1]=new Stock("Google","GOGL",323.98);
    }

}

```

Answer: 
You can't execute code in the class definition body. 

You have to either declare attributes or method. Additionally ( as in your case ) you can create free floating blocks where you **can** execute code, that's why the first two didn't work but the third did. 

```
class A { 
   private int i;
   i = 10; // illegal
}

class A { 
   private int i;
   { i = 10; } // ok, free floating code
}

```

The free floating block of code will be executed when the instance is created. Most of the times this is unneeded because that kind of initialization goes better in the class constructor.

If used with static modifier it will be executed when the class is loaded.

One common use of it is for anonymous classes as a substitute for constructor, for instance in Swing, this is somewhat common when building prototypes. 

```
JPanel p = new JPanel(){{ //<-- free floating code aka double initialization idiom.
    add( new JLabel("A"));
    add( new JLabel("B"));
}};

```
As mentioned already, the initializations are not valid outside a method construct or outside a block as this violates the programming syntax. Pls do refer to any good java book.