Why is this Java program showing no error?

Consider the below code,

I forgot to define the method name, just the code within the block.

public class Demo {

    {
    Apple ap;
    // Display price of Winesap.
    System.out.println("Winesap costs " + Apple.Winesap.getPrice()
            + " cents.\n");
    // Display all apples and prices.
    System.out.println("All apple prices:");
    for (Apple a : Apple.values())
        System.out.println(a + " costs " + a.getPrice() + " cents.");
    }

}

is it because blocks{} in java defines a scope?

A block {} defines the scope in Java. Each time you start a new block, you are creating a new scope. A scope determines what objects are visible to other parts of the program. It also determines the lifetime of these objects. Many other computer languages define 2 general category of scopes : global and local.

Jon Skeet
people
quotationmark

What you've got there is an instance initializer, as described by section 8.6 of the JLS.

It's executed before the body of any constructor when an instance is created - just like field initializers.

people

See more on this question at Stackoverflow