sixtytrees sixtytrees - 5 months ago 9
Java Question

Minimizing the scope of a variable in do ... while loop [Java] - ERROR: Symbol cannot be found

I would like to minimize the scope of

to a
do ... while
loop, so it can be destroyed once the loop is exited.

If I declare
within the
do while
loop, I get the error:

symbol cannot be found

I can declare it right before the cycle, but then I keep bloated
in memory even though I don't need it any more.

//int[] arr = {0}; // this works, but the scope is outside the loop
do {
int[] arr = {0}; // causes "cannot find symbol" on `while` line
arr = evolve(arr); // modifies array, saves relevant results elsewhere
} while (arr.length < 9999);

What is the correct way to deal with this situation?


You have:

  • An initial state
  • A terminating state
  • An iterative operation

So you have everything needed to use a for loop (albeit without a body):

for (int[] arr = {0}; arr.length < 9999; arr = evolve(arr));

Another solution, but nowhere near as neat, is to add this after the loop:

arr = null;

which still allows the allocated memory to be garbage collected and has a similar practical effect to restricting scope. Sometimes you need this approach if you can't refactor the code another way.