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.