Markus Mitterauer Markus Mitterauer - 1 year ago 66
Java Question

Is it possible to declare a variable within a Java while conditional?

In Java it is possible to declare a variable in the initialization part of a


for ( int i=0; i < 10; i++) {
// do something (with i)

But with the
statement this seems not to be possible.

Quite often I see code like this, when the conditional for the while loop needs to be updated after every iteration:

List<Object> processables = retrieveProcessableItems(..); // initial fetch
while (processables.size() > 0) {
// process items
processables = retrieveProcessableItems(..); // update

Here on stackoverflow I found at least a solution to prevent the duplicate code of fetching the processable items:

List<Object> processables;
while ((processables = retrieveProcessableItems(..)).size() > 0) {
// process items

But the variable still has to be declared outside the while-loop.

So, as I want to keep my variable scopes clean, is it possible to declare a variable within the while conditional, or is there some other solution for such cases?

Answer Source

You can write a while loop using a for loop:

while (condition) { ... }

is the same as

for (; condition; ) { ... }

since all three bits in the brackets of the basic for statement declaration are optional:

    for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

Similarly, you can just rewrite your while loop as a for loop:

for (List<Object> processables;
     (processables = retrieveProcessableItems(..)).size() > 0;) {
  // ... Process items.

Note that some static analysis tools (e.g. eclipse 4.5) might demand that an initial value is assigned to processables, e.g. List<Object> processables = null. This is incorrect, according to JLS; my version of javac does not complain if the variable is left initially unassigned.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download