I saw a piece of code in a book, which is as follows:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
a scope is where you can refer to a variable.
a block defines a block scope
a variable defined inside a block will be defined only inside that block and you can't reference it after the end of block.
so in this code if you try something like:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
y = 5; // error y is out of scope, not it is not defined
because what you have here is a local scope
other kinds of scope in java are class scope
(for example), a member of a class has a class scope so it is accessible anywhere inside a class.
the basic rules for scope are: