Is it possible to declare a variable in Java while conditionally?

In Java, you can declare a variable in the for -loop initialization part:

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

But with a while statement, this seems impossible.

Quite often, I see this code when the conditional value of the while loop should be updated after each iteration:

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

Here at stackoverflow, I found at least a solution to prevent code duplication to extract processed elements:

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

But the variable still needs to be declared outside the while loop.

So, since I want my variable areas to be clean, is it possible to declare a variable in a conditional expression, or is there some other solution for such cases?

+6
source share
2 answers

You can write a while using the for loop:

 while (condition) { ... } 

coincides with

 for (; condition; ) { ... } 

since all three bits in basic brackets are optional for operator declaration :

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

Similarly, you can simply rewrite the while 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) may require that the initial value be assigned to processables , for example. List<Object> processables = null . This is not true according to JLS; my javac version does not complain if the variable on the left is not initially assigned.

+8
source

No, It is Immpossible.

This also doesn’t make much sense: unlike the for loop, where you can set the initial state of the "cyclic variable", in the while you check the value of an existing variable, akin to conditionally checking the for loop.

Of course, if you are worried that the variables are β€œleaking” to other parts of your code, you can enclose all this in an additional scope block:

 { /*declare variable here*/ while(...){...} } 

Alternatively, convert the while to a for loop.

+4
source

All Articles