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

浪子不回头ぞ 提交于 2019-12-05 02:28:02

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:

BasicForStatement:
    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.

No it's not possible.

It doesn't really make too much sense either: unlike a for loop where you can set up the initial state of the "looping variable", in a while loop you test the value of an existing variable, akin to the conditional check of the for loop.

Of course, if you're concerned about variables "leaking" into other parts of your code, you could enclose the whole thing in an extra scope block:

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

Alternatively, convert the while loop into a for loop.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!