Java Reference
In-Depth Information
Another important remark concerns the fact that local and parameter variables are forgotten once
their scope is exited, meaning that method arguments will disappear once you exit the method (this
allows you to use the same variable name for arguments throughout different methods), just as local
variables will be discarded once the compiler steps out of its block (a method or loop body). To illus-
trate this once more, consider the following:
class ScopeTest {
void scopeTest(int a) {
int b = a + 10;
for (int c = 0; c < 10; c++) {
int d = c + 3;
b = b + 1;
}
}
}
Try to work out what is happening here. Variable d (local variable) is only accessible within the loop
block. Variable c (parameter variable) is initialized for each iteration of the loop and is only acces-
sible within the loop body. Variable b (local variable) is discarded after the method is exited but is
accessible in the whole method. Variable a (parameter variable) is also discarded after the method is
exited and is accessible in the whole method, but it's passed as a method argument.
Note If you want to do so, note that you can also arbitrarily create your own
scope blocks, different from class, method, or loop bodies. This is done simply
by wrapping a piece—a block—of code in curly brackets: { and } . For example,
the previous code snippet can be extended as such:
class ScopeTest {
void scopeTest(int a) {
int b = a + 10;
for (int c = 0; c < 10; c++) {
int d = c + 3;
{
int e = d + 3;
}
// e not accessible here
b = b + 1;
}
// c not accessible here
{
int c = 3;
}
// c also not accessible here
}
}
While this is an often forgotten tidbit of Java that can come in handy to struc-
ture complex pieces of code, it's best not to rely on this feature too much.
When you find yourself putting large amounts of code in blocks like this, it is
probably a good idea to try to separate some behavior into multiple methods
or classes to split things up.
Search WWH ::




Custom Search