1

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.

Marko Topolnik
  • 188,298
  • 27
  • 302
  • 416
Farhan Shirgill Ansari
  • 13,530
  • 10
  • 51
  • 100

1 Answers1

4

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.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049