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
  • 195,646
  • 29
  • 319
  • 436
Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105

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,421,763
  • 867
  • 9,128
  • 9,194