Re: Which scope for variables being used in a loop?
"Manish Pandit" wrote ...
In this case, the variables are allocated on the stack, as they are
"local". I do not think this could lead to out of memory (unless the
collection is gigantic). Personally I never like the idea of declaring
variables within a loop, and have not seen a lot of instances where it
is done.
There are plenty of instances where variables are declared inside a loop, and
there are good, solid engineering reasons to do so.
Declaring the variable inside a loop, or any other block, limits its scope to
that block. If it is not needed outside the block, then its scope matches its
use.
The variable remains in the JVM until the end of the stack frame, even after
it goes out of scope; if it isn't nulled then it won't be gced until the
method ends. It is still inaccessible to code outside its block.
Limiting variable scope is a good principle of defensive programming. If a
variable doesn't linger after its use, nor is declared until needed, it has
less chance to make mischief. (Joshua Bloch touches on this in /Effective Java/.)
Use of the for ( T thing : things ) idiom is an example of scope limitation.
The variable "thing" is only in scope for the loop.
- Lew